1

到目前为止,我一直在测试我的 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 是否分配了正确的数据(如果有)。这很好地达到了这个目的,但它没有做的是测试我的路由是否像 ZF1Zend_Test_PHPUnit_Controller_TestCase测试一样正常工作。

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

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

4

2 回答 2

5

我参加聚会迟到了,但它仍然对新手有用。现在的解决方案是继承自\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)以及其他与网络相关的方法。

于 2013-03-06T02:20:30.153 回答
-1

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

于 2012-10-10T03:48:17.060 回答