5

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

コントローラーアクション内でリダイレクトを行っているためです。リダイレクトを行わなければ、単体テストは機能します。何か案は?

4

1 に答える 1

6

これは、セットアップで行う必要があったことです。

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);
}
于 2012-09-25T16:35:10.360 に答える