Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing parameters to PHPUnit

Tags:

php

phpunit

I'm starting to write PHPUnit tests and I'd like the tests to be run from developers machines as well as from our servers. Developers machines are set up differently than the servers and even differently from each other.

To run in these different places it seems to be the person that runs the test is going to have to indicate where it's being run. The test can then look up the proper config of the machine it's running on.

I'm imagining something like:

phpunit.bat -X johns_laptop unittest.php

or on the alpha server:

phpunit -X alpha unittest.php

In the test I would be able to get the value if the 'X' (or whatever it is) parameter and know, for example, what the path to the app root is for this machine.

It doesn't look like the command line allows for that - or have I missed something?

like image 747
dl__ Avatar asked Jan 19 '10 16:01

dl__


3 Answers

You can use PHPUnit's --bootstrap switch for this.

--bootstrap <file>       A "bootstrap" PHP file that is run before the tests. 

Then, make a bootstrap.php file that contains variables:

$port = 4445; 

In your tests, you can grab those values:

global $port; $this->setPort($port); 

Then run:

phpunit --bootstrap boot.php MyTest.php 
like image 80
Mark Theunissen Avatar answered Oct 14 '22 19:10

Mark Theunissen


One way would be for you to inspect $argv and $argc. Something like:

<?php  require_once 'PHPUnit/Framework/TestCase.php';  class EnvironmentTest extends PHPUnit_Framework_TestCase {     public function testHasParam() {             global $argv, $argc;             $this->assertGreaterThan(2, $argc, 'No environment name passed');             $environment = $argv[2];     } } 

Then you can call your phpunittest like this:

phpunit EnvironmentTest.php my-computer 
like image 36
Paolo Avatar answered Oct 14 '22 17:10

Paolo


An elegant way to pass variables to both bootstrap files as well as to test files is by using environment variables:

export MY_ENV_VAR="some value"

phpunit all

Then, in your PHP files, you can access it like this:

getenv('MY_ENV_VAR')

Source: http://blog.lysender.com/2010/10/phpunit-passing-environment-variable-to-your-application/

like image 23
scribu Avatar answered Oct 14 '22 18:10

scribu