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
這是因爲我做的是控制器內部重定向。如果我不做重定向,單元測試工作。有任何想法嗎?
看起來很像http://stackoverflow.com/questions/12570377/how-can-i-pass-extra的間接副本-parameters-to-the-routematch-object –
我建議看看如何實例化路由器對象,然後將其添加到MvcEvent中,因爲URL插件需要這個。我認爲一個好的起點是SimpleRouteStack類,它實現了正在檢查的接口。 – DrBeza