Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force an environment variable to a certain value inside phpunit test?

In my phpunit I have this configuration:

<php>
    <env name="ENVIRONMENT" value="test"/>
</php>

I worked under the false assumption that it always would set the environment variable to the value test. Yet when the system already has the variable set, then it prefers the already existing value.

$ export ENVIRONMENT=GNARF
$ phpunit -c test/phpunit.xml

So inside the tests the value of env('ENVIRONMENT') will be "GNARF" even though I expected "test".

Is there a way to make phpunit to treat the env setting not as a default but rather as the definite value it should be using?

I also would like to avoid calling phpunit in a certain way just to get the right env variables.

So while this works:

ENVIRONMENT="test";./vendor/bin/phpunit -c tests/phpunit.xml

I rather configure it inside the phpunit.xml file if possible.

like image 463
k0pernikus Avatar asked Feb 18 '16 10:02

k0pernikus


People also ask

How do I change the value of an environment variable?

To modify an existing environment variable: In the User variables section, select the environment variable you want to modify. Click Edit to open the Edit User Variable dialog box. Change the value of the variable and click OK.

Can environment variables change during execution?

No. This is not possible. One process can never directly manipulate the environment of a different already-running process.


3 Answers

This way worked for me (tested with PHPUnit 6.5):

<phpunit bootstrap="vendor/autoload.php">
    <testsuites>
        <testsuite name="MyProject">
            <directory>tests</directory>
        </testsuite>
    </testsuites>
    <php>
        <env name="API_KEY" value="fakeApiKey" force="true" />
    </php>
</phpunit>

Here's the pull request where they added this new feature (in case you're interested).

sebastianbergmann added this to the PHPUnit 6.3 milestone on 4 Jul 2017

like image 61
Francesco Casula Avatar answered Sep 24 '22 18:09

Francesco Casula


The environment variables are set in PHPUnit_Util_Configuration::handlePHPConfiguration() and indeed, it looks like this:

foreach ($configuration['env'] as $name => $value) {
    if (false === getenv($name)) {
        putenv("{$name}={$value}");
    }
    if (!isset($_ENV[$name])) {
        $_ENV[$name] = $value;
    }
}

As it seems, there is no way to circumvent this check without unsetting the variable first. And while you're at it, you could as well set it to the desired value immediately.

like image 36
Fabian Schmengler Avatar answered Sep 25 '22 18:09

Fabian Schmengler


You can set the env vars from the bootstrap file. The bootstrap file can be selected from the phpunit.xml file so the result would be what you're looking for.

like image 37
gontrollez Avatar answered Sep 25 '22 18:09

gontrollez