2010-12-04 100 views
5

荫100%的代码覆盖率的粉丝,但我不知道如何测试Zend框架的ErrorController。单元测试误差控制在Zend框架

这是没有问题的测试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'); 

} 

回答

0

嗯,我不是很熟悉这个问题,但我会用操作的自定义ErrorHandler插件这种行为(延续原来,并且假装抛出异常)。也许有可能只注册一次测试。

1

这是一个老问题,但我与今日挣扎,但没有找到一个很好的答案其他地方,所以我会继续前进,后我做了什么来解决这个问题。答案其实很简单。

点你的派遣行动将导致抛出异常。

当一个GET请求的JSON终点做,所以我用其中的一个,以测试这我的应用程序抛出一个错误。

/** 
    * @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); 
    }