Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony 2 w/ PhpUnit 3.6 : changing target hostname for test purposes

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 !

like image 566
user772843 Avatar asked Nov 07 '11 15:11

user772843


3 Answers

You can also pass HTTP_HOST in server parameters to change the target host name:

self::createClient(array(), array(
    'HTTP_HOST' => 'sample.host.com',
));
like image 132
Karol Kasprzak Avatar answered Nov 08 '22 08:11

Karol Kasprzak


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();
like image 31
Arno Avatar answered Nov 08 '22 08:11

Arno


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'));
like image 7
igorw Avatar answered Nov 08 '22 06:11

igorw