首页 > 解决方案 > Lumen 8 不使用 .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.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 缺少的内容中添加我的所有配置?我应该怎么办?

标签: phplaravelapiunit-testinglumen

解决方案


您正在将环境文件加载到新的存储库实例中,但您的 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();

如果您bootstrap/app.php使用此代码更新文件,则可以在phpunit.xml文件中指定一个环境变量以将APP_ENV变量设置为testing. 如果你这样做,上面的代码将加载.env.testing文件。

注意:所有理论都基于阅读代码。未经测试。


推荐阅读