繁体   English   中英

ZF2 / ZF2中的路由测试相当于Zend_Test_PHPUnit_Controller_TestCase?

[英]Routing tests in ZF2 / ZF2 equivalent of Zend_Test_PHPUnit_Controller_TestCase?

到目前为止,我一直在测试我的ZF2控制器如下:

namespace Application\Controller;

use Application\Controller\IndexController;
use Zend\Http\Request;
use Zend\Http\Response;
use Zend\Mvc\MvcEvent;
use Zend\Mvc\Router\RouteMatch;
use PHPUnit_Framework_TestCase;

class IndexControllerTest extends PHPUnit_Framework_TestCase
{
    public function testIndexActionCanBeAccessed()
    {
        $this->routeMatch->setParam('action', 'index');

        $result   = $this->controller->dispatch($this->request);
        $response = $this->controller->getResponse();

        $this->assertEquals(200, $response->getStatusCode());
        $this->assertInstanceOf('Zend\View\Model\ViewModel', $result);
    }

    protected function setUp()
    {
        \Zend\Mvc\Application::init(include 'config/application.config.php');

        $this->controller = new IndexController();
        $this->request    = new Request();
        $this->routeMatch = new RouteMatch(array('controller' => 'index'));
        $this->event      = new MvcEvent();
        $this->event->setRouteMatch($this->routeMatch);
        $this->controller->setEvent($this->event);
    }

    protected $controller = null;
    protected $event = null;
    protected $request = null;
    protected $response = null;
    protected $routeMatch = null;
}

这允许我测试ViewModel在呈现视图之前是否具有分配给它的正确数据(如果有)。 这个目的很好,但它没有做的是测试我的路由是否正常工作,如ZF1 Zend_Test_PHPUnit_Controller_TestCase测试。

在那些,我通过运行$this->dispatch('/some/relative/url')测试,并且只有在路由设置正确的情况下才能获得正测试结果。 通过这些ZF2测试,我特别告诉它使用哪条路由,这并不一定意味着真正的请求将被正确路由。

如何在ZF2中测试我的路由是否正常工作?

我迟到了,但它对新手来说仍然有用。 现在的解决方案是继承自\\Zend\\Test\\PHPUnit\\Controller\\AbstractControllerTestCase ,因此用法与ZF1非常相似:

class IndexControllerTest extends \Zend\Test\PHPUnit\Controller\AbstractHttpControllerTestCase
{
    public function setUp()
    {
        $this->setApplicationConfig(
                include __DIR__ . '/../../../../../config/application.config.php'
        );
        parent::setUp();
    }

    public function testIndexActionCanBeAccessed()
    {
        $this->dispatch('/');

        $this->assertResponseStatusCode(200);
        $this->assertModuleName('application');
        $this->assertControllerName('application\controller\index');
        $this->assertControllerClass('IndexController');
        $this->assertMatchedRouteName('home');

        $this->assertQuery('html > head');
    }
}

注意:这使用\\Zend\\Test\\PHPUnit\\Controller\\AbstractHttpControllerTestCase ,其中包括assertQuery($path)以及其他与Web相关的方法。

编辑: ZF2已经更新,因为我自己回答了这个问题。 PowerKiki的答案更好。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM