【发布时间】:2017-11-28 09:01:48
【问题描述】:
我要测试的方法有一个 try catch 之类的
try {
$fooClass->doStuff(); // Throws \Lib\Custom\Exception
}
catch (\Lib\Custom\Exception $exception) {
return false;
}
我想测试返回是否为假,但是执行我的测试时没有加载自定义异常。
Php 单元可以选择模拟类,但我似乎无法将其用于异常。
$exceptionMock= $this->getMockBuilder(\Lib\Custom\Exception::class)->getMock();
$fooClassMock = $this->getMockBuilder(fooClass::class)->getMock()
->method('doStuff')
->willThrowException($exceptionMock);
给我以下异常:
Argument 1 passed to
PHPUnit_Framework_MockObject_Builder_InvocationMocker::willThrowException()
must be an instance of Exception, instance of Mock_Exception_c4dd9394 given
如何正确地模拟这个异常来测试功能?
【问题讨论】:
-
你的
\Lib\Custom\Exception扩展\Exception吗? -
是的,但它不在 composer.json 自动加载中。
-
所以当创建模拟时,它似乎不是
\Exception的子级。 -
是的,模拟不是一种异常。有一天,这可能是对 phpUnit 模拟的一个很好的补充。但现在我将把 lib 添加到我的自动加载器中。