[英]Lumen 8 not using .env.testing
我正在使用 Lumen 8。我想使用.env.testing
中的配置,但它总是读取.env
中的配置
测试/TestCase.php
<?php
use Dotenv\Dotenv;
abstract class TestCase extends Tests\Utilities\UnitTest\Testing\TestCase
{
public static function setUpBeforeClass(): void
{
Dotenv::createImmutable(dirname(__DIR__), '.env.testing')->load();
parent::setUpBeforeClass();
}
public function createApplication()
{
return require __DIR__ . '/../bootstrap/app.php';
}
}
.env.测试
APP_ENV=testing
APP_DEBUG=false
DB_CONNECTION=mysql
DB_HOST=db_testing
DB_PORT=3307
DB_DATABASE=db_testing
DB_USERNAME=db_username
DB_PASSWORD=db_password
.env
APP_ENV=local
APP_DEBUG=false
DB_CONNECTION=mysql
DB_HOST=db
DB_PORT=3307
DB_DATABASE=db_local
DB_USERNAME=db_username
DB_PASSWORD=db_password
当我调试像dd(DB::connection()->getDatabaseName());
这样的测试文件时它返回db_local
而不是db_testing
我不想在phpunit.xml
中添加我的所有配置 缺少什么? 我应该怎么办?
您正在将您的环境文件加载到一个新的存储库实例中,但是您的 lumen 应用程序不知道该存储库实例存在。
接下来,当您的bootstrap/app.php
文件运行时,它将创建存储库实例,其中加载了 lumen 知道如何使用的普通.env
文件。
最干净的解决方案可能是删除您的setUpBeforeClass()
方法并仅更新您的bootstrap/app.php
文件以支持加载不同的 .env 文件。
一个例子:
$env = env('APP_ENV');
$file = '.env.'.$env;
// If the specific environment file doesn't exist, null out the $file variable.
if (!file_exists(dirname(__DIR__).'/'.$file)) {
$file = null;
}
// Pass in the .env file to load. If no specific environment file
// should be loaded, the $file parameter should be null.
(new Laravel\Lumen\Bootstrap\LoadEnvironmentVariables(
dirname(__DIR__),
$file
))->bootstrap();
如果使用此代码更新bootstrap/app.php
文件,则可以在phpunit.xml
文件中指定一个环境变量,以将APP_ENV
变量设置为testing
。 如果这样做,上面的代码将加载.env.testing
文件。
注意:所有理论都基于阅读代码。 未经测试。
非常有趣的是,流明在删除了工匠支持后不支持动态环境文件名,问题链接
所以基本上你必须 go 手动模式
在你的 bootstrap.app 文件中
// boostrap.php
(new Laravel\Lumen\Bootstrap\LoadEnvironmentVariables(
\dirname(__DIR__),
))->bootstrap();
class LoadEnvironmentVariables
{
protected $filePath;
protected $fileName;
// change the $name, i.e the env file name to your env file manually
public function __construct($path, $name = null)
{
$this->filePath = $path;
$this->fileName = $name;
}
....
这是另一个可能有帮助的链接
@patricus 答案的简化版本:
使用以下更改更新您的bootstrap/app.php
:
$env_file = '.env.' . env('APP_ENV');
(new Laravel\Lumen\Bootstrap\LoadEnvironmentVariables(
dirname(__DIR__), file_exists(dirname(__DIR__) . '/' . $env_file) ? $env_file : null
))->bootstrap();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.