簡體   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