In situations where apps behave differently based on environment variables (e.g. getenv()
and putenv()
), the EnvironmentVariables
trait creates fixtures to manipulate these variables while resetting them between tests.
Set or update an environment variable for the duration of the test.
setEnvironmentVariable(string $key[, mixed $value = null]): self
This is a wrapper around PHP's putenv()
function.
- $key
- The environment variable name.
- $value
- The value to set for the environment variable. Default is
null
- Passing
NULL
to$value
will remove the environment variable.
This method will return the calling class, enabling multiple methods to be chained.
Delete/unset an environment variable for a single test.
deleteEnvironmentVariable(string $key): bool
This is equivalent to calling $this->setEnvironmentVariable($key, null)
.
- $key
- The environment variable name.
This method will return the calling class, enabling multiple methods to be chained.
Imagine we have a function, greet_user()
, which tries to read the user's name from the username
environment variable:
use AssertWell\PHPUnitGlobalState\EnvironmentVariables;
use PHPUnit\Framework\TestCase;
class MyTestClass extends TestCase
{
use EnvironmentVariables;
/**
* @test
*/
public function greetings_should_include_the_username_env_var()
{
$this->setEnvironmentVariable('username', 'Test McTest');
$this->assertSame('Hello, Test McTest!', greet_user());
}
}
Regardless of whether or not greetings_should_include_the_username_env_var()
passes, the username
environment variable will be reset after the test method completes.