Ronni Egeriis Persson
Ronni Egeriis Persson

Reputation: 2289

How to test exception handler with phpspec

I am stumbling a bit with finding a way to test that my exception handler is being called upon thrown Exception.

This is the idea that I initially working with for the testing:

class ClientSpec extends ObjectBehavior
{
    function it_should_catch_exceptions(Config $config)
    {
        $e = new Exception('test exception');
        $this->catchException($e)->shouldBeCalled();
        throw $e;
    }
}

The Client has a method catchException which will be set as exception handler through set_exception_handler: http://php.net/set_exception_handler.

Running this test gives me this feedback: no beCalled([array:0]) matcher found for null, so I've also tried to do create a spec for Exception and do the following:

class ExceptionSpec extends ObjectBehavior
{
    function it_should_trigger_opbeat_client_when_thrown(Client $client)
    {
        $client->catchException($this)->shouldBeCalled();
        throw $this->getWrappedObject();
    }
}

But running this test returns another error: exception [exc:Exception("")] has been thrown

How can I test that my exception handler is called?

Upvotes: 4

Views: 818

Answers (1)

axiac
axiac

Reputation: 72226

I'm afraid you cannot test an exception handler using phpspec, PHPUnit or other similar testing tool because they wrap the test you write into a try-catch block in order to catch any uncaught exception and report it.

On the other hand, the documentation of set_expection_handler() says:

Sets the default exception handler if an exception is not caught within a try/catch block.

Since phpspec catches all the exceptions your test code throws, the exception handler you install does not have a chance to run :-(

I think all uncaught exceptions end their adventure in ExampleRunner.php at line 96

Upvotes: 1

Related Questions