2012-10-08 79 views
1

到目前爲止,我一直在測試我的ZF2控制器如下:ZF2/ZF2等價於Zend_Test_PHPUnit_Controller_TestCase的路由測試?

namespace Application\Controller; 

use Application\Controller\IndexController; 
use Zend\Http\Request; 
use Zend\Http\Response; 
use Zend\Mvc\MvcEvent; 
use Zend\Mvc\Router\RouteMatch; 
use PHPUnit_Framework_TestCase; 

class IndexControllerTest extends PHPUnit_Framework_TestCase 
{ 
    public function testIndexActionCanBeAccessed() 
    { 
     $this->routeMatch->setParam('action', 'index'); 

     $result = $this->controller->dispatch($this->request); 
     $response = $this->controller->getResponse(); 

     $this->assertEquals(200, $response->getStatusCode()); 
     $this->assertInstanceOf('Zend\View\Model\ViewModel', $result); 
    } 

    protected function setUp() 
    { 
     \Zend\Mvc\Application::init(include 'config/application.config.php'); 

     $this->controller = new IndexController(); 
     $this->request = new Request(); 
     $this->routeMatch = new RouteMatch(array('controller' => 'index')); 
     $this->event  = new MvcEvent(); 
     $this->event->setRouteMatch($this->routeMatch); 
     $this->controller->setEvent($this->event); 
    } 

    protected $controller = null; 
    protected $event = null; 
    protected $request = null; 
    protected $response = null; 
    protected $routeMatch = null; 
} 

這讓我測試視圖模型是有正確的數據(如果有的話)分配給它的視圖顯示之前。這樣做的目的很好,但它沒有做的是測試我的路由工作正常,就像ZF1 Zend_Test_PHPUnit_Controller_TestCase測試一樣。

其中,我會通過運行$this->dispatch('/some/relative/url')開始測試,並且只有在路線設置正確的情況下才能獲得積極的測試結果。通過這些ZF2測試,我具體告訴它要使用哪條路線,這並不一定意味着真正的請求將被正確路由。

如何測試我的路由在ZF2中正常工作?

回答

5

我很晚參加派對,但它對新來者仍然有用。該解決方案現在將來自\Zend\Test\PHPUnit\Controller\AbstractControllerTestCase繼承,所以使用會非常相似,ZF1:

class IndexControllerTest extends \Zend\Test\PHPUnit\Controller\AbstractHttpControllerTestCase 
{ 
    public function setUp() 
    { 
     $this->setApplicationConfig(
       include __DIR__ . '/../../../../../config/application.config.php' 
     ); 
     parent::setUp(); 
    } 

    public function testIndexActionCanBeAccessed() 
    { 
     $this->dispatch('/'); 

     $this->assertResponseStatusCode(200); 
     $this->assertModuleName('application'); 
     $this->assertControllerName('application\controller\index'); 
     $this->assertControllerClass('IndexController'); 
     $this->assertMatchedRouteName('home'); 

     $this->assertQuery('html > head'); 
    } 
} 

注:這使用\Zend\Test\PHPUnit\Controller\AbstractHttpControllerTestCase包括assertQuery($path)以及其他網絡相關的方法。

+0

由於AbstractHttpControllerTestCase :: dispatch()不返回任何內容,實際上不允許測試控制器分派的返回值。 –

+1

@EricMORAND,不$ this-> getResponse() - > getContent()允許你測試任何需要測試的東西嗎? – PowerKiKi

-1

編輯: ZF2已經更新,因爲我自我回答這個。 PowerKiki's answer比較好。