Symfony 2 w / PhpUnit 3.6: changing the target host name for testing purposes

I am testing the controller this way:

$crawler = $client->request('GET', 'lang/120'); 

After print_r'ing the $ crawler object, I see that the destination URL is http: // localhost / lang / 120 . However, my target host is the virtual host installed on my machine, say http: //www.somehost.tld , and I would like to use it. What clean tools should I use for my unit tests to target this virtual host?

I tried to put the php variable in the 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 it looks awkward ... Is there any configuration file (config_test file?) Where should I put this virtual host name?

Thanks for the help, everyone!

+7
source share
3 answers

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

 self::createClient(array(), array( 'HTTP_HOST' => 'sample.host.com', )); 
+12
source

You can set these values ​​as DIC (Container 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 

You can then create a helper method in your test class to get the URL for a specific host:

 private function getHostUrl($hostId, $path = '') { return self::$kernel->getContainer()->getParameter('myapp.test.hostname.'.$hostId).$path; } 

Note. I assume you are using WebTestCase .

Finally, use this in your test:

 $crawler = $client->request('GET', $this->getHostUrl('somehost', '/lang/120')); 
+6
source

According to igorw, if you have a hostname as a parameter in the configuration file, for example:

 #config/config_test.yml parameters: myapp_hostname: "http://www.myapp.com" 

In WebTestCase, you can get the host name from the parameters and set the HTTP_HOST parameter for the client:

 $client = self::createClient(); $hostname = $client->getContainer()->getParameter('myapp_hostname'); $client->setServerParameter('HTTP_HOST', $hostname ); $client->request('GET', '/lang/120'); 

In your test code, the Request object contains the host name:

 'http://www.myapp.com/lang/120' === $request->getUri(); 
+2
source

All Articles