Zend Framework 2如何在控制器动作中测试重定向?

Ric*_*nop 5 php phpunit zend-framework2

如何使用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());
    }

}
Run Code Online (Sandbox Code Playgroud)

上面的代码在运行单元测试时导致此错误:

Zend\Mvc\Exception\DomainException: Url plugin requires that controller event compose a router; none found
Run Code Online (Sandbox Code Playgroud)

这是因为我在控制器动作中进行重定向.如果我不进行重定向,则单元测试工作正常.有任何想法吗?

Ric*_*nop 6

这是我需要在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);
}
Run Code Online (Sandbox Code Playgroud)