简体   繁体   中英

How to test internal controllers without route in Symfony 2

I am trying to reduce redundant code by refactoring template and controller code into reusable components, which I then use via the render(controller('AppBundle:Foo/Bar:baz')) construct inside my other templates.

Of course I would like to test these components. In the examples regarding functional testing, however, an actual route is required to make fake test requests. But my BarController here is purely internal and has no routes attached to it. How can I test this controller?

Creating dummy routes is not always possible, because some of the arguments are model objects that cannot be passed via URL. Am I approaching this the wrong way?

If the controllers are setup as services, then they can be easily tested much as any other class would be unit-tested. Even before Symfony 3.3 started to make them services by default, I had altered some of my own to allow them to be more easily tested like this.

The service approach sounds nice, but I am simply doing this now:

self::$kernel->getContainer()->get('router')->getContext()->setParameter('_locale', 'en');

$controller = new MyController();
$controller->setContainer(self::$kernel->getContainer());

$response = $controller->myAction($arg1, $arg2, $argWhatever);

// assertions here

Seems to work just fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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