[英]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.