【问题标题】:UnitTest Error Controller in Zend FrameworkZend 框架中的 UnitTest 错误控制器
【发布时间】:2012-06-16 03:13:42
【问题描述】:

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

测试404Action和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');

}

【问题讨论】:

    标签: zend-framework phpunit


    【解决方案1】:

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

    将您的调度指向将导致抛出异常的操作。

    当对 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);
        }
    

    【讨论】:

      【解决方案2】:

      好吧,我对这个主题不是很熟悉,但我会使用自定义 ErrorHandler 插件来操纵这种行为(扩展原始插件,并假装抛出异常)。也许可以只为一项测试注册它。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-02-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-22
        • 2013-09-27
        相关资源
        最近更新 更多