Dan*_*iel 5 php phpunit mocking environment-variables laravel
我正在实现一些需要代码在生产环境中表现不同的逻辑。
我想编写一个测试来断言这确实发生了,但是我很难模拟环境。
我已经看到建议使用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);
}
}
Run Code Online (Sandbox Code Playgroud)
时间:160 毫秒,内存:18.00MB
有 1 次失败:
1) 环境测试::testEnv
断言两个字符串相等失败。
- - 预期的
+++ 实际
@@@@
-'生产'
+'测试'
use App;
//...
public function my_awesome_test()
{
// Number of times method environment() have to be invoked
$number_of_calls_to_method = 2
// Fake, that we have production environment
App::shouldReceive('environment')
->times($number_of_calls_to_method)
->andReturn('production');
// Make here whatever you want in Production environment
}
Run Code Online (Sandbox Code Playgroud)
我知道这个问题已经过去一年了,但是对于那些看起来像我一样的人来说,这在 5.8 中对我有用
public function test_config_env()
{
$this->app->detectEnvironment(function() {
return 'production';
});
$this->assertEquals('production', app()->environment()); // pass
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2422 次 |
| 最近记录: |