2017-11-28 09:01
浏览 131


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()

Gives me the folowing exception:

Argument 1 passed to 
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; 


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> 


PHPUnit_Framework_MockObject_Builder_InvocationMocker :: willThrowException()
must是异常的实例,实例 Mock_Exception_c4dd9394给出


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

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()
         ->willThrowException(new \Lib\Custom\Exception());

    Or something similar..

    打赏 评论

相关推荐 更多相似问题