如何在 phpunit 测试中将环境变量强制为某个值?

问题描述 投票:0回答:4

在我的 phpunit 中我有这样的配置:

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

我在错误的假设下工作,它总是将环境变量设置为值

test
。然而,当系统已经设置了变量时,它会更喜欢已经存在的值。

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

所以在测试中,

env('ENVIRONMENT')
的值将是
"GNARF"
,尽管我预期是
"test"
.

有没有办法让 phpunit 将

env
设置视为它应该使用的确定值而不是默认值?

我也想避免以某种方式调用 phpunit 只是为了获得正确的环境变量。

所以虽然这有效:

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

如果可能的话,我宁愿在

phpunit.xml
文件中配置它。

php phpunit environment-variables
4个回答
34
投票

这种方式对我有用(使用 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>

这是拉取请求,他们在其中添加了这个新功能(如果您感兴趣的话)。

sebastianbergmann 于 2017 年 7 月 4 日将此添加到 PHPUnit 6.3 里程碑


3
投票

环境变量在

PHPUnit_Util_Configuration::handlePHPConfiguration()
中设置,实际上,它看起来像这样:

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

看起来,如果不先取消设置变量,就无法绕过此检查。当您使用它时,您也可以立即将其设置为所需的值。


1
投票

您可以从

env
文件中设置
bootstrap
变量。可以从
phpunit.xml
文件中选择引导程序文件,这样结果就是您要查找的内容。


0
投票

这就是我在 Laravel\Lumen 中制作它的方式。我想测试代码在不同环境下的行为:

private function provideData(): array
{
    return [
        'tc_1'    => ['production', 'in', 'in'],
        'tc_2'    => ['development', 'in', 'str'],
        'tc_3'    => ['testing', 'in', 'str'],
    ];
}

/**
 * @dataProvider provideData
 * @return void
 */
public function testProvidedData(string $env, string $inStr, string $outStr)
{
    $_ENV['APP_ENV'] = $env;
    $this->assertSame($outStr, Class::method($inStr));
}

在 Class::method() 中,代码如下所示:

public static function method(string $inStr): string
{
    return (env('APP_ENV') === "production")
        ? $inStr
        : 'str';
}
© www.soinside.com 2019 - 2024. All rights reserved.