我正在使用Lumen 8。我想使用.env.testing内部的配置,但它总是读取.env内部的配置
tests/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.testing
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中,什么是缺失的?我该怎么办?
发布于 2021-01-14 04:49:58
您正在将您的环境文件加载到一个新的存储库实例中,但是您的流明应用程序不知道存储库实例的存在。
接下来,当您的bootstrap/app.php文件运行时,它将创建包含普通.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文件。
注:所有的理论都是基于阅读代码。未经测试。
发布于 2021-01-14 04:32:51
非常有趣的是,在删除了工匠支持,链接到问题之后,鲁门不支持动态环境文件名
所以基本上你必须采用手动模式
在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;
}
....这是另一个可能是帮助的链接
发布于 2022-01-20 14:11:44
@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();https://stackoverflow.com/questions/65713265
复制相似问题