2011-11-16 57 views
4

乳寧所有測試的Zend應用程序時,這條線:Zend_Controller_Response_Exception:無法發送標題;

protected function _getResp() 
{ 
    if (is_null($this->_response)) 
     $this->_response = new Zend_Controller_Response_Http(); 
    return $this->_response; 
} 
....... 
$this->_getResp()->setHeader('Content-Type', 'text/html; charset=utf-8', true); 

生成以下錯誤:

Zend_Controller_Response_Exception: Cannot send headers; headers already sent in /usr/share/php5/PEAR/PHPUnit/Util/Printer.php, line 173

和作爲一個結果 - 測試失敗

+0

請參閱http://stackoverflow.com/questions/190292/phpunit-unit-testing-with-items-that-need-to-send-headers – ManseUK

回答

3

這是因爲PHPUnit的之前生成輸出引起你的測試甚至運行。您需要在測試用例中注入Zend_Controller_Response_HttpTestCase。這個Zend_Controller_Response_Http的子類實際上並不發送標題或輸出任何內容,也不會拋出異常,因爲它不關心輸出已經發送。

只需將以下方法添加到上述類中即可。

public function setResp(Zend_Controller_Response_Http $resp) { 
    $this->_response = $resp; 
} 

創建一個新的Zend_Controller_Response_HttpTestCase並將它傳遞給setResp()正在測試的對象。這也將允許您驗證正確的標題與輸出一起「發送」。

+0

我知道這有點古老,但您需要寫這個?我有同樣的確切問題,但我不明白從你的答案我應該在哪裏寫這些行,我也在ControllerTestCase的主引導中嘗試過,但沒有運氣 – Uffo

+0

您正在使用'Zend_Test_PHPUnit_ControllerTestCase'嗎?它在'bootstrap()'中將'Zend_Controller_Response_HttpTestCase'響應注入到前端控制器中。 –

+0

我還沒有看到Uffo問題的答案(我也有這個問題)。 setResp函數進入哪個文件?我試着將代碼添加到Zend_Test_PHPUnit_ControllerTestCase中,但它不起作用。 – blainarmstrong

0

在我的情況下,我有自定義請求和響應對象:My_Controller_Request_RestMy_Controller_Response_Rest。我創建了一個新的My_Controller_Request_RestTestCaseMy_Controller_Response_RestTestCase,分別擴展了Zend_Controller_Request_HttpTestCaseZend_Controller_Response_HttpTestCase

什麼David Harkness建議實際上解決了這個問題。唯一的事情是你的對象必須擴展對應於每個類的HttpTestCase類。

您需要爲每個對象創建setter,因爲您不允許直接設置它們。

我有以下ControllerTestCase代碼:

tests/application/controllers/ControllerTestCase.php

abstract class ControllerTestCase extends Zend_Test_PHPUnit_ControllerTestCase 
{ 
    /** 
    * Application instance. 
    * @var Zend_Application 
    */ 
    protected $application; 

    /** 
    * Setup test suite. 
    * 
    * @return void 
    */ 
    public function setUp() 
    { 
     $this->_setupInitializers(); 
     $this->bootstrap = array(
      $this, 
      'applicationBootstrap', 
     ); 
     parent::setUp(); 

     $this->setRequest(new My_Controller_Request_RestTestCase()); 
     $this->setResponse(new My_Controller_Response_RestTestCase()); 
    } 
} 

我定製的請求和響應對象具有以下特徵:

library/My/Controller/Request/Rest.php

class My_Controller_Request_Rest extends Zend_Controller_Request_Http 
{ 
    // Nothing fancy. 
} 

現在

class Bonzai_Controller_Response_Rest extends Zend_Controller_Response_Http 
{ 
    // Nothing fancy either 
} 

,這是我無法弄清楚,如何避免library/My/Controller/Request/Rest.phplibrary/My/Controller/Controller/Request/RestTestCase.php重複相同的代碼。在我的情況下,在Request/Rest.php和Request/RestTestCase.php以及Response/Rest.php和Response/RestTestCase.php中的代碼是相同的,但它們擴展爲Zend_Controller_(Request|Response)_HttpTestCase

我希望我明確自己。我知道這個帖子已經過時了,但我認爲有必要再擴展一下。

相關問題