How can I test a redirect in a controller action with PHPUnit?
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());
}
}
The above code causes this error when I run unit tests:
Zend\Mvc\Exception\DomainException: Url plugin requires that controller event compose a router; none found
It's because I am doing a redirect inside the controller action. If I don't do a redirect, unit tests work. Any ideas?
This is what I needed to do in the setUp:
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With