0

我正在关注关于 zend 框架 2的入门教程,在它建议使用测试的主题之一中,它建议的代码是:

namespace ApplicationTest\Controller;

use ApplicationTest\Bootstrap;
use Zend\Mvc\Router\Http\TreeRouteStack as HttpRouter;
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
{
    protected $controller;
    protected $request;
    protected $response;
    protected $routeMatch;
    protected $event;

    protected function setUp()
    {
        $serviceManager = Bootstrap::getServiceManager();
        $this->controller = new IndexController();
        $this->request    = new Request();
        $this->routeMatch = new RouteMatch(array('controller' => 'index'));
        $this->event      = new MvcEvent();
        $config = $serviceManager->get('Config');
        $routerConfig = isset($config['router']) ? $config['router'] : array();
        $router = HttpRouter::factory($routerConfig);

        $this->event->setRouter($router);
        $this->event->setRouteMatch($this->routeMatch);
        $this->controller->setEvent($this->event);
        $this->controller->setServiceLocator($serviceManager);
    }
    public function testIndexActionCanBeAccessed()
    {
        $this->routeMatch->setParam('action', 'index');

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

        $this->assertEquals(200, $response->getStatusCode());        

    }
}

如您所见,没有__autoload($class).

为了手动使其工作,我添加了include "../../Bootstrap.php";它确实解决了问题,但我记得一旦我可以让这段代码工作,并且教程似乎没有忘记概念上明显的东西并且在主题评论中没有关于它的反馈,可能有是我想念的东西,上面的代码可能会如何工作?

4

1 回答 1

0

我设法让它工作,但注意到你不能使用 phpUnit 的扩展请求和响应对象。这些是早期 2.0 版本的说明。至少在 2.0.7 之后,指令有很大不同,代码也更干净:

http://zf2.readthedocs.org/en/latest/user-guide/unit-testing.html

<?php

namespace ApplicationTest\Controller;

use Zend\Test\PHPUnit\Controller\AbstractHttpControllerTestCase;

class IndexControllerTest extends AbstractHttpControllerTestCase
{
    public function setUp()
    {
        $this->setApplicationConfig(
            include '/path/to/application/config/test/application.config.php'
        );
        parent::setUp();
    }

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

        $this->assertModuleName('application');
        $this->assertControllerName('application_index');
        $this->assertControllerClass('IndexController');
        $this->assertMatchedRouteName('home');
    }
}

在这个例子中,测试是通过扩展 Zend 的控制器测试用例来进行的,这是使用 zf1 进行控制器测试的方式。

于 2013-05-14T10:27:16.420 回答