2010-12-04 38 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); 
    }