【问题标题】:Zend Framework 2 how to test redirect in controller action?Zend Framework 2 如何在控制器动作中测试重定向?
【发布时间】:2012-09-17 03:12:14
【问题描述】:

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

}

上面的代码在我运行单元测试时会导致这个错误:

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

这是因为我在控制器操作中进行了重定向。如果我不做重定向,单元测试就可以工作。有什么想法吗?

【问题讨论】:

  • 看起来很像stackoverflow.com/questions/12570377/…的间接复制
  • 我建议查看如何实例化路由器对象,然后将其添加到 MvcEvent,因为 URL 插件需要这样做。我想一个很好的起点是 SimpleRouteStack 类,因为它实现了正在检查的接口。

标签: php phpunit zend-framework2


【解决方案1】:

这是我需要在设置中做的:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-22
    • 2013-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多