Zend framework Zend框架中的UnitTest错误控制器

Zend framework Zend框架中的UnitTest错误控制器,zend-framework,phpunit,Zend Framework,Phpunit,我是100%代码覆盖率的粉丝,但我不知道如何在Zend框架中测试ErrorController 测试404动作和errorAction没有问题: public function testDispatchErrorAction() { $this->dispatch('/error/error'); $this->assertResponseCode(200); $this->assertController('er

我是100%代码覆盖率的粉丝,但我不知道如何在Zend框架中测试ErrorController

测试404动作和errorAction没有问题:

    public function testDispatchErrorAction()
    {
        $this->dispatch('/error/error');
        $this->assertResponseCode(200);
        $this->assertController('error');
        $this->assertAction('error');
    }

    public function testDispatch404()
    {
        $this->dispatch('/error/errorxxxxx');
        $this->assertResponseCode(404);
        $this->assertController('error');
        $this->assertAction('error');
    }
但是如何测试应用程序错误(500)? 也许我需要这样的东西

public function testDispatch500()
{
    throw new Exception('test');

    $this->dispatch('/error/error');
    $this->assertResponseCode(500);
    $this->assertController('error');
    $this->assertAction('error');

}

嗯,我对这个主题不是很熟悉,但我会用一个定制的ErrorHandler插件(扩展原来的插件,并假装抛出了异常)来处理这个行为。也许只在一次测试中注册它是可能的。

这是一个老问题,但我今天一直在努力解决这个问题,在其他任何地方都找不到好的答案,所以我将继续并发布我解决这个问题的方法。答案其实很简单

将调度指向将导致引发异常的操作

当向JSON端点发出get请求时,我的应用程序会抛出一个错误,所以我使用了其中一个来测试这一点

   /**
   * @covers  ErrorController::errorAction
   */
    public function testErrorAction500() {
        /**
         * Requesting a page that doesn't exist returns the proper error message 
         */
        $this->dispatch('/my-json-controller/json-end-point');
        $body = $this->getResponse()->getBody();
        $this->assertResponseCode('500');
        $this->assertContains('Application error',$body);
    }
或者,如果您不介意让一个动作仅仅用于测试,您可以创建一个只抛出错误的动作,并在单元测试中指向该动作

public function errorAction() {
    throw new Exception('You should not be here');
}
那么您的测试将如下所示:

   /**
   * @covers  ErrorController::errorAction
   */
    public function testErrorAction500() {
        /**
         * Requesting a page that doesn't exist returns the proper error message 
         */
        $this->dispatch('/my-error-controller/error');
        $body = $this->getResponse()->getBody();
        $this->assertResponseCode('500');
        $this->assertContains('Application error',$body);
    }