简体   繁体   English

如何在Symfony 2中无路由地测试内部控制器

[英]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. 我试图通过将模板和控制器代码重构为可重用的组件来减少冗余代码,然后通过其他模板中的render(controller('AppBundle:Foo/Bar:baz'))构造使用这些组件。

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. 但是我的BarController完全是内部的,没有附加任何路由。 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. 创建虚拟路由并非总是可能的,因为某些参数是无法通过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. 甚至在Symfony 3.3开始默认提供它们的服务之前,我已经更改了一些自己的东西,以使它们可以像这样更容易地进行测试。

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. 似乎工作正常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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