【问题标题】:PHPUnit testing an exception flow of executionPHPUnit 测试异常执行流程
【发布时间】:2014-07-21 09:35:26
【问题描述】:

我猜这是一个常见问题,但我无法决定如何解决。

我有一个有 4 个 catch 块的公共函数。在每个 catch 块中,一个私有方法被调用如下

public function updateInformation(){

 try{
    .....
  }catch(Zend_Http_Client_Exception $e){
    $this->somePrivateMethod1();
  }catch(Zend_Service_Exception $e){
    $this->somePrivateMethod2();
  }catch(UnexpectedValueException $e){
    $this->somePrivateMethod3();
  }catch(Exception $e){
    $this->somePrivateMethod4();
  }

}

我正在编写测试用例来测试updateInformation() 函数。我也想测试异常块,这样我也可以测试私有方法。我如何实现这一目标?因此,代码覆盖率也被折腾了。

【问题讨论】:

  • 我提供了一个答案,概述了您需要做什么的基础知识。但是有关您正在测试的课程的更多信息将有助于提供更详细的答案。

标签: unit-testing phpunit private-members test-coverage


【解决方案1】:

您有一个依赖项抛出异常,以便您的代码捕获它。

http://phpunit.de/manual/current/en/phpunit-book.html#test-doubles.stubs.examples.StubTest8.php

public function testThrowExceptionStub()
    {
        // Create a stub for the SomeClass class.
        $stub = $this->getMock('SomeClass');

        // Configure the stub.
        $stub->method('doSomething')
             ->will($this->throwException(new Exception));

        $sut = new Class($stub);

        $sut->updateInformation();

        //DO MORE ASSERTIONS ABOUT BEHAVIOR IN PRIVATE METHODS

    }
}

我假设try 块中有一些东西需要被模拟。如果没有,则设置类以满足条件,从而引发异常。

【讨论】:

    猜你喜欢
    • 2019-07-12
    • 2014-07-07
    • 2015-10-17
    • 2016-04-27
    • 1970-01-01
    • 1970-01-01
    • 2018-05-05
    • 2011-03-29
    • 2012-03-20
    相关资源
    最近更新 更多