I am testing a controller in that fashion :
$crawler = $client->request('GET', 'lang/120');
Upon print_r'ing the $crawler object I can see that the target URL is http://localhost/lang/120. However, my target host is a virtual host set up on my machine, let's say http://www.somehost.tld and I'd like to use that. What clean means should I use for my unit tests to target that virtual host ?
I have tried putting a php variable in my phpunit.xml.dist file and use it :
<php>
<server name="HOSTNAME" value="http://www.somehost.tld/app.php/" />
</php>
And then :
$crawler = $client->request('GET', $_SERVER['HOSTNAME'] . 'lang/120');
But that looks awkward...Is there any config file (the config_test file ?) where I should put that virtual hostname ?
Thanks for helping, everyone !
You can also pass HTTP_HOST in server parameters to change the target host name:
self::createClient(array(), array(
'HTTP_HOST' => 'sample.host.com',
));
According to igorw, if you have your hostname as parameter in a config file, like :
#config/config_test.yml
parameters:
myapp_hostname: "http://www.myapp.com"
In your WebTestCase, you can get the hostname from parameters, and set the HTTP_HOST parameter to client :
$client = self::createClient();
$hostname = $client->getContainer()->getParameter('myapp_hostname');
$client->setServerParameter('HTTP_HOST', $hostname );
$client->request('GET', '/lang/120');
In your code to test, the Request object contains the hostname :
'http://www.myapp.com/lang/120' === $request->getUri();
You could set those values as DIC (Dependency Injection Container) parameters in config/config_test.yml
.
Basically just add them like this:
parameters:
myapp.test.hostname.somehost: http://www.somehost.tld
myapp.test.hostname.otherhost: https://www.otherhost.tld
Then you can create a helper method on your test class to get the url for a certain host:
private function getHostUrl($hostId, $path = '')
{
return self::$kernel->getContainer()->getParameter('myapp.test.hostname.'.$hostId).$path;
}
Note: I'll assume that you are using the WebTestCase
.
Finally, make use of this in your test:
$crawler = $client->request('GET', $this->getHostUrl('somehost', '/lang/120'));
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