Highly Opinionated Thoughts on Programming

by Elnur Abdurrakhimov


Using Environment Variables to Add Flexibility to PHPUnit Tests

May 20, 2014


If you’re using PHPUnit for running not only unit but UI tests too, you might want to be able to run them against different browsers. There are several ways of doing that, some of which involve hardcoding some stuff in your phpunit.xml or having multiple phpunit.xx.yml files or, worse, hardcoding it in the tests themselves.

The way I found to work great for me is the usage of environment variables.

Did you know you could run a command in a shell with an environment variable set specifically for it?

$ BROWSER=firefox phpunit

This approach is more flexible compared to setting an environment variable for the whole shell session and then resetting it each time you need a different value.

We could take advantage of this approach for our testing. Suppose you have a way of choosing a different browser:

1
2
3
4
5
6
7
8
9
10
11
class TestCase extends PHPUnit_Framework_TestCase
{
    private $browser;

    protected function setUp()
    {
        $this->browser = new Browser('firefox');
    }

    // ...
}

Now the browser name is hardcoded. We could move it to phpunit.xml to set a default:

1
2
3
4
5
<phpunit>
    <php>
        <env name="BROWSER" value="firefox"/>
    </php>
</phpunit>

Then our test case would get the browser name from the environment:

1
2
3
4
5
6
7
8
9
10
11
class TestCase extends PHPUnit_Framework_TestCase
{
    private $browser;

    protected function setUp()
    {
        $this->browser = new Browser(getenv('BROWSER'));
    }

    // ...
}

And if we wanted to run the same tests for a different browser, we could do it easily:

$ BROWSER=chrome phpunit


© Elnur Abdurrakhimov