4

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?

Ronni Egeriis Persson
  • 2,209
  • 1
  • 21
  • 43

1 Answers1

1

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

axiac
  • 68,258
  • 9
  • 99
  • 134
  • Thank you for your answer. I was going nuts trying to find a solution to this. While the answer is disappointing, it will prompt me to find an alternative solution for testing this. – Ronni Egeriis Persson Mar 05 '15 at 12:22
  • There are two aspects here: first, you want to test that the exception handler does its job properly. You can use `phpspec` or other testing tool to test the behavior of the handler function by calling it directly with the correct argument. Second, the test you posted checks if the handler is installed correctly. Installing it should not be the responsibility of the `Client` class itself. It should be part of the application bootstrap, on the same level as the setup of the autoloading, for example. And you could just rely on the fact that PHP will call your handler, if one is installed. – axiac Mar 05 '15 at 12:40