Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zend Framework 2 how to test redirect in controller action?

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?

like image 213
Richard Knop Avatar asked Sep 25 '12 14:09

Richard Knop


1 Answers

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);
}
like image 95
Richard Knop Avatar answered Sep 27 '22 22:09

Richard Knop