我正在实现一些需要代码在生产环境中表现不同的逻辑。
我想编写一个测试来断言这确实发生了,但是我很难模拟环境。
我已经 seen it suggested使用 putenv('APP_ENV=production');
但它似乎不起作用。
我怎样才能通过测试?
use Illuminate\Support\Facades\App;
use Tests\TestCase;
class EnvTest extends TestCase
{
public function testEnv()
{
// This assertion is fine
$env = App::environment();
$this->assertEquals('testing', $env);
putenv('APP_ENV=production');
// This assertion fails
$env = App::environment();
$this->assertEquals('production', $env);
}
}
结果
Time: 160 ms, Memory: 18.00MB
There was 1 failure:
1) EnvTest::testEnv
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-'production'
+'testing'
最佳答案
我知道这个问题已经过去一年了,但是对于那些看起来像我一样的人来说,这在 5.8 中对我有用
public function test_config_env()
{
$this->app->detectEnvironment(function() {
return 'production';
});
$this->assertEquals('production', app()->environment()); // pass
}
关于php - 在测试中模拟 Laravel 环境,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50843693/