Ken*_*eth 2 php api unit-testing laravel lumen
我正在使用 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';
}
}
Run Code Online (Sandbox Code Playgroud)
.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
Run Code Online (Sandbox Code Playgroud)
.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
Run Code Online (Sandbox Code Playgroud)
当我调试测试文件时,
dd(DB::connection()->getDatabaseName());
它返回db_local而不是db_testing
我不想在phpunit.xml
缺少的内容中添加所有配置?我该怎么办?
您正在将环境文件加载到新的存储库实例中,但您的 lumen 应用程序不知道存储库实例存在。
接下来,当您的bootstrap/app.php文件运行时,它会创建一个存储库实例,该存储库实例加载了.envlumen 知道如何使用的普通文件。
最干净的解决方案可能是删除您的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();
Run Code Online (Sandbox Code Playgroud)
如果bootstrap/app.php使用此代码更新文件,则可以在phpunit.xml文件中指定一个环境变量以将该APP_ENV变量设置为testing. 如果这样做,上面的代码将加载.env.testing文件。
注意:所有理论都基于阅读代码。未经测试。
| 归档时间: |
|
| 查看次数: |
481 次 |
| 最近记录: |