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

在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?

图片转代码服务由CSDN问答提供 功能建议

我尝试测试的方法有一个像

 <  code> try {
 $ fooClass-&gt; doStuff();  //抛出\ Lib \ Custom \ Exception 
} 
catch(\ Lib \ Custom \ Exception $ exception){
 return false; 
} 
   
 
 

我想测试返回是否为false,但是在执行测试时没有加载自定义异常。

Php单元可以选择模拟类,但我似乎无法 用于例外。

  $ exceptionMock = $ this-&gt; getMockBuilder(\ Lib \ Custom \ Exception :: class) - &gt; getMock(); 
 
  $ fooClassMock = $ this-&gt; getMockBuilder(fooClass :: class) - &gt; getMock()
  - &gt;方法('doStuff')
  - &gt; willThrowException($ exceptionMock); 
  <  / pre> 
 
 

给我以下异常:

 参数1传递给
PHPUnit_Framework_MockObject_Builder_InvocationMocker :: willThrowException()
must是异常的实例,实例 Mock_Exception_c4dd9394给出
   
 
 

如何正确模拟此Exception以测试函数?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

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.

    已采纳该答案
    打赏 评论
  • dongmubi4375 2017-11-28 09:14

    I don't think you need to mock the exception.

    why not try this?

    $fooClassMock = $this->getMockBuilder(fooClass::class)->getMock()
         ->method('doStuff')
         ->willThrowException(new \Lib\Custom\Exception());
    

    Or something similar..

    打赏 评论

相关推荐 更多相似问题