gpt4 book ai didi

php - Zend Framework 2 如何在 Controller 操作中测试重定向?

转载 作者:可可西里 更新时间:2023-11-01 14:04:09 25 4
gpt4 key购买 nike

如何使用 PHPUnit 测试 Controller 操作中的重定向?

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

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

最佳答案

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

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

关于php - Zend Framework 2 如何在 Controller 操作中测试重定向?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12585711/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com