Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. My test class extends from WebTestCase. I use the static::createClient() to get an operational client.

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. But that doesn't work as I have myproject.local as host.

$client->getContainer()->get('kernel')->getRootDir() and other dir method provide linux file path, not web path.

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?

like image 645
Aurélien B Avatar asked Mar 19 '13 08:03

Aurélien B


2 Answers

Symfony2's built in test framework (WebTestCase) only needs the relative path to be able to test applications in different environments:

$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. There are no web servers involved.

You can read more about how the client simulation works here: http://symfony.com/doc/current/book/testing.html#working-with-the-test-client

like image 94
james_t Avatar answered Oct 21 '22 20:10

james_t


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.

"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."

See more info here: http://symfony.com/doc/current/book/testing.html#working-with-the-test-client

like image 21
honzalilak Avatar answered Oct 21 '22 18:10

honzalilak