phpspec / prophecy

Highly opinionated mocking framework for PHP 5.3+
MIT License
8.53k stars 240 forks source link

Prophecy exception hidden by generic exception catch in application code #301

Open fabianaromagnoli opened 7 years ago

fabianaromagnoli commented 7 years ago

Hi, given this method of a class under test:

public function run(array $items)
{
    foreach ($items as $item) {
        try {
            $this->doSomethingThatCouldThrowAnyException($item);
            $this->myProphecy->doSomething();
        } catch (Exception $e) {
            continue;
        }
    }
}

I have a test that mocks myProphecy behaviour. If I don't set any expectation on this mock, prophecy throws a \Prophecy\Exception\Call\UnexpectedCallException, but this exception is caught and hidden by the catch in the application code. I need to catch a generic exception, and not a specific one, because I need the iteration to process all items, even if something for a specific item goes wrong. What can I do to make test properly fail when expectations are not met?

stof commented 7 years ago

Well, if your code swallows all exceptions silently, there is nothing you can do, except stopping this. Btw, the same will be true for all other mocking libraries out there AFAIK.

fabianaromagnoli commented 7 years ago

Ok, I suspected that there is nothing to do, but I wanted to be 100% sure. Thanks a lot for your answer.

ciaranmcnulty commented 7 years ago

You could rethrow prophecy exceptions:

        } catch (Exception $e) {
            if ($e instanceof \Prophecy\Exception) {
                throw $e;
            }
            continue;
        }
fabianaromagnoli commented 7 years ago

Yes, this is a possible solution, but we discarded it because we don't want to mess testing code in application code. Thanks for the suggestion.