2012-09-25 14 views
5

PHPUnitでコントローラーアクションのリダイレクトをテストするにはどうすればよいですか?Zend Framework 2コントローラアクションでリダイレクトをテストする方法は?

class IndexControllerTest extends PHPUnit_Framework_TestCase 
{ 

    protected $_controller; 
    protected $_request; 
    protected $_response; 
    protected $_routeMatch; 
    protected $_event; 

    public function setUp() 
    { 
     $this->_controller = new IndexController; 
     $this->_request = new Request; 
     $this->_response = new Response; 
     $this->_routeMatch = new RouteMatch(array('controller' => 'index')); 
     $this->_routeMatch->setMatchedRouteName('default'); 
     $this->_event = new MvcEvent(); 
     $this->_event->setRouteMatch($this->_routeMatch); 
     $this->_controller->setEvent($this->_event); 
    } 

    public function testIndexActionRedirectsToLoginPageWhenNotLoggedIn() 
    { 
     $this->_controller->dispatch($this->_request, $this->_response); 
     $this->assertEquals(200, $this->_response->getStatusCode()); 
    } 

} 

上記のコードは、私はユニットテストを実行すると、このエラーが発生します。私は、コントローラのアクション内のリダイレクトをやっているので、

Zend\Mvc\Exception\DomainException: Url plugin requires that controller event compose a router; none found 

にです。私がリダイレクトをしなければ、単体テストが動作します。何か案は?

+0

はかなりhttp://stackoverflow.com/questions/12570377/how-can-i-pass-extraの間接的な重複のように思えます-parameters-to-the-routematch-object –

+1

ルータオブジェクトのインスタンスを作成し、それをURLプラグインが必要とするためMvcEventに追加する方法を検討することをお勧めします。私は良い出発点SimpleRouteStackクラスは、それがチェックされているインターフェイスを実装すると思います。 – DrBeza

答えて

6

これは私がセットアップで行うために必要なものです:

public function setUp() 
{ 
    $this->_controller = new IndexController; 
    $this->_request = new Request; 
    $this->_response = new Response; 

    $this->_event = new MvcEvent(); 

    $routeStack = new SimpleRouteStack; 
    $route = new Segment('/admin/[:controller/[:action/]]'); 
    $routeStack->addRoute('admin', $route); 
    $this->_event->setRouter($routeStack); 

    $routeMatch = new RouteMatch(array('controller' => 'index', 'action' => 'index')); 
    $routeMatch->setMatchedRouteName('admin'); 
    $this->_event->setRouteMatch($routeMatch); 

    $this->_controller->setEvent($this->_event); 
} 
関連する問題