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?
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With