ZF2 PHPUnit在AbstractHttpControllerTestCase Helper方法中断言异常

时间:2014-12-29 21:58:48

标签: exception-handling zend-framework2 phpunit

如果不是调度操作,如何测试此方法中是否抛出异常? (这将发生在AbstractHttpControllerTestCase对Controller的单元测试中。)

public function myMethodHelper($status, $message) {
    throw new DomainException($status, $message);
}

尝试使用try / catch不会捕获异常,但会在抛出的异常中结束(错误而不是失败):

/**
 * @covers Application\Controller\MyController::myMethodHelper
 */
public function testMyMethodHelper() {
    // $this->object is instantiated in setUp() as the Controller to be tested.
    try {
        $this->object->myMethodHelper(500, 'The message to check.');
    } catch (\Zend\Stdlib\Exception\DomainException $exc) {
        $this->assertEquals($exc-getMessage(), 'The message to check.');
    }
}

1 个答案:

答案 0 :(得分:0)

在使用Zend Framework 2.3和AbstractHttpControllerTestCase时,我能够使用以下注释断言异常,消息和异常代码(假设我返回一个带有错误代码500的DomainException作为示例):

/**
 * @covers Application\Controller\MyController::myMethodHelper
 * @expectedException Zend\Stdlib\Exception\DomainException
 * @expectedExceptionMessage The message to check.
 * @expectedExceptionCode 500
 */
public function testMyMethodHelper() {
    // Annotations deal with expected exception, so no code is needed.
    $this->object->responder(500, 'The message to check.');
    $this->fail('Exception failed to be thrown.');
}