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.
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.
No. This is not possible. One process can never directly manipulate the environment of a different already-running process.
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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With