简体   繁体   English

symfony2控制器的功能测试:如何生成路由

[英]Functional test of a symfony2 controller: How to generate a route

On a symfony2 controller, I would like to test a controller, which return a Response object. 在symfony2控制器上,我想测试一个返回Response对象的控制器。 My test class extends from WebTestCase . 我的测试类扩展自WebTestCase I use the static::createClient() to get an operational client. 我使用static::createClient()来获取一个可操作的客户端。

My problem is to call the good route on my current installation with a virtual host. 我的问题是使用虚拟主机在当前安装上调用好路由

$client->getContainer()->get('router')->generate('my_route', array(), true) generate a route with localhost as host. $client->getContainer()->get('router')->generate('my_route', array(), true)生成一个localhost作为主机的路由。 But that doesn't work as I have myproject.local as host. 但这不起作用,因为我有myproject.local作为主机。

$client->getContainer()->get('kernel')->getRootDir() and other dir method provide linux file path, not web path. $client->getContainer()->get('kernel')->getRootDir()和其他dir方法提供linux文件路径,而不是web路径。

I cannot hard code it as I am not alone on the project. 我不能硬编码,因为我并不孤单。 So what is the method to get the correct route, or is there another way to test the controller? 那么获得正确路由的方法是什么,还是有另一种方法来测试控制器?

Symfony2's built in test framework (WebTestCase) only needs the relative path to be able to test applications in different environments: Symfony2的内置测试框架(WebTestCase)只需要能够在不同环境中测试应用程序的相对路径:

$client->getContainer()->get('router')->generate('my_route', array(), false);

Symfony simulates an http client and tests against an instance of the Kernel created for that test. Symfony模拟http客户端,并针对为该测试创建的内核实例进行测试。 There are no web servers involved. 没有涉及Web服务器。

You can read more about how the client simulation works here: http://symfony.com/doc/current/book/testing.html#working-with-the-test-client 您可以在此处详细了解客户端模拟的工作原理: http//symfony.com/doc/current/book/testing.html#working-with-the-test-client

As mentioned in Symfony documentation, you should use absolute urls, because change of URLs will impact your end users and thats what you wanna cover in your functional tests too. 正如Symfony文档中所提到的,您应该使用绝对URL,因为URL的更改将影响您的最终用户,这也是您在功能测试中想要涵盖的内容。

"Hardcoding the request URLs is a best practice for functional tests. If the test generates URLs using the Symfony router, it won't detect any change made to the application URLs which may impact the end users." “硬编码请求URL是功能测试的最佳实践。如果测试使用Symfony路由器生成URL,它将不会检测到可能影响最终用户的应用程序URL的任何更改。”

See more info here: http://symfony.com/doc/current/book/testing.html#working-with-the-test-client 在此处查看更多信息: http//symfony.com/doc/current/book/testing.html#working-with-the-test-client

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

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