2012-09-25 3 views
5

Wie kann ich eine Umleitung in einer Controller-Aktion mit PHPUnit testen?Zend Framework 2 Testen der Weiterleitung in Controller-Aktion?

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()); 
    } 

} 

Der obige Code verursacht diesen Fehler, wenn ich Unit-Tests laufen:

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

Es ist, weil ich eine Umleitung in der Controller-Aktion tue. Wenn ich keine Umleitung mache, funktionieren die Komponententests. Irgendwelche Ideen?

+0

scheint viel hübsch wie ein indirektes Duplikat http://stackoverflow.com/questions/12570377/how-can-i-pass-extra -parameters-to-the-routematch-object –

+1

Ich würde vorschlagen, zu untersuchen, wie das Router-Objekt instanziiert wird, und es dann dem MvcEvent hinzuzufügen, da das URL-Plugin dies erfordert. Ich würde mir vorstellen, dass ein guter Startpunkt die SimpleRouteStack-Klasse wäre, die die Schnittstelle implementiert, nach der geprüft wird. – DrBeza

Antwort

6

Dies ist, was ich in der setUp tun musste:

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); 
}