dongzj2015 2017-11-28 09:01
浏览 151
已采纳

在phpUnit中模拟异常

The method I am trying to test has a try catch like

try {
    $fooClass->doStuff(); // Throws \Lib\Custom\Exception
} 
catch (\Lib\Custom\Exception $exception) {
    return false;
}

I want to test if the return is false, but the custom exception is not loaded when my tests are executed.

Php unit has the option of mocking classes, but I can't seem to use this for Exceptions.

$exceptionMock= $this->getMockBuilder(\Lib\Custom\Exception::class)->getMock();

$fooClassMock = $this->getMockBuilder(fooClass::class)->getMock()
     ->method('doStuff')
     ->willThrowException($exceptionMock);

Gives me the folowing exception:

Argument 1 passed to 
PHPUnit_Framework_MockObject_Builder_InvocationMocker::willThrowException() 
must be an instance of Exception, instance of Mock_Exception_c4dd9394 given

How to properly mock this Exception to test the function?

  • 写回答

2条回答 默认 最新

  • dtkz3186 2017-11-28 17:49
    关注

    The reason that your test isn't working is because the class isn't known in the test. When that happens and you create a mock in PHPUnit, it does some trickery to create a class definition and then extends that to create the mock. Otherwise it would use the extend the class itself and you would not have had a problem.

    In this case, PHPUnit creates a fake \Lib\Custom\Exception and then uses that to create the mock. The fake class created doesn't extend anything (since it wouldn't know what to extend/implement). So the type hint in the willThrowException will not be matched because your mock object didn't extend Exception.

    This would happen with any type hinting for extended classes in PHPUnit if the class is not loaded in the test. In order to fix this, you need to have the class available in the test via a require, include, or autoloader.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度