我找到一种方法来测试我的异常处理程序在抛出异常时被调用,我有点磕磕绊绊.
这是我最初合作进行测试的想法:
class ClientSpec extends ObjectBehavior { function it_should_catch_exceptions(Config $config) { $e = new Exception('test exception'); $this->catchException($e)->shouldBeCalled(); throw $e; } }
客户端有一个方法catchException,它将通过set_exception_handler:http://php.net/set_exception_handler设置为异常处理程序.
运行此测试给了我这样的反馈:没有beCalled([array:0])找到null的匹配器,所以我也尝试为Exception创建一个规范并执行以下操作:
class ExceptionSpec extends ObjectBehavior { function it_should_trigger_opbeat_client_when_thrown(Client $client) { $client->catchException($this)->shouldBeCalled(); throw $this->getWrappedObject(); } }
但运行此测试会返回另一个错误:异常[exc:Exception(“”)]已被抛出
如何测试我的异常处理程序是否被调用?
解决方法
我担心您无法使用phpspec,PHPUnit或其他类似的测试工具测试异常处理程序,因为它们将您编写的测试包装到try-catch块中以捕获任何未捕获的异常并报告它.
另一方面,set_expection_handler()
的文档说:
Sets the default exception handler if an exception is not caught within a try/catch block.
由于phpspec捕获了测试代码抛出的所有异常,因此您安装的异常处理程序没有机会运行:-(
我认为所有未被捕获的例外都会在ExampleRunner.php
at line 96结束他们的冒险