添加测试控制器和路由以测试事件侦听器

时间:2014-09-07 14:19:26

标签: symfony

如何在Symfony包中测试事件监听器?

我计划用客户端测试它(发送请求并获得响应)。但我的捆绑中没有控制器。我可以添加特殊的'从功能测试和测试输出的控制器和路由?

1 个答案:

答案 0 :(得分:2)

我已经找到了如何添加控制器进行测试的方法。

首先 - 创建新的控制器类(我在%BundleName%/ Tests / Controller中创建它)

%BUNDLENAME%/测试/控制器/ TestController.php

namespace %BundleName%\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;

class TestController extends Controller
{
    public function rootAction()
    {
        return new Response('This is home page');
    }

    public function galleryAction($id)
    {
        return new Response(sprintf('This is gallery %s', $id));
    }
} 

然后我在测试中使用了这个控制器。

%BUNDLENAME%/测试/控制器/ PageControllerTest.php

namespace %BundleName%\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\Routing\Route;

class PageControllerTest extends WebTestCase
{
    /**
     * @var \Symfony\Bundle\FrameworkBundle\Client
     */
    private $client;

    public function setUp()
    {
        $this->client = static::createClient();
        $this->client->followRedirects(true);
        $this->setUpRoutes();
    }

    public function testFirst()
    {
        $crawler = $this->client->request('GET', '/gallery/42');
    }

    protected function setUpRoutes()
    {
        $container = $this->client->getContainer();

        /** @var \Symfony\Bundle\FrameworkBundle\Routing\Router $router */
        $router = $container->get('router');
        $collection = $router->getRouteCollection();

        foreach ($collection->all() as $routeId => $route) {
            //Leave some routes if you need... 

            $collection->remove($routeId);
        }

        $controllerClassName = '\%BundleName%\Tests\Controller\TestController';

        $rootRoute = new Route('/', array('_controller' => sprintf('%s::%s', $controllerClassName, 'rootAction')));
        $galleryRoute = new Route('/gallery/{id}', array('_controller' => sprintf('%s::%s', $controllerClassName, 'galleryAction')));

        $collection->add('_test_root_route', $rootRoute);
        $collection->add('_test_gallery_route', $galleryRoute);
    }
}

在每个测试开始时,setUpRoutes方法清除路由列表并注册新路由。每个路由_controller参数值为\%BundleName%\Tests\Controller\TestController::nameOfAction'