为什么在 运行 测试时缺少 "default" 数据源连接?

Why is the "default" datasource connection missing when running tests?

我正在按照 here.

所述使用固定装置编写测试

我的 bootstrap 测试:

if (!getenv('db_dsn')) {
    putenv('db_dsn=sqlite:///:memory:');
}

ConnectionManager::config('test', ['url' => getenv('db_dsn')]);
ConnectionManager::config('test_custom_i18n_datasource', ['url' => getenv('db_dsn')]);

我的代码:

use Cake\TestSuite\TestCase;

class BackupExportTest extends TestCase
{
    public $fixtures = ['core.articles', 'core.comments'];

    public function setUp()
    {
        parent::setUp();
        $this->Articles = \Cake\ORM\TableRegistry::get('Articles');
    }

    public function testMyFunction()
    {
        $query = $this->Articles->find('all');
    }
}

现在,运行测试,这是例外情况:

PHPUnit 5.4.6 by Sebastian Bergmann and contributors.

E                                                                   1 / 1 (100%)

Time: 62 ms, Memory: 4.00MB

There was 1 error:

1) MysqlBackup\Test\TestCase\Utility\BackupExportTest::testMyFunction
Cake\Datasource\Exception\MissingDatasourceConfigException: The datasource configuration "default" was not found.

/home/mirko/Libs/Plugins/cakephp-mysql-backup/vendor/cakephp/cakephp/src/Datasource/ConnectionManager.php:196
/home/mirko/Libs/Plugins/cakephp-mysql-backup/vendor/cakephp/cakephp/src/ORM/Locator/TableLocator.php:175
/home/mirko/Libs/Plugins/cakephp-mysql-backup/vendor/cakephp/cakephp/src/ORM/TableRegistry.php:110
/home/mirko/Libs/Plugins/cakephp-mysql-backup/tests/TestCase/Utility/BackupExportTest.php:38

ERRORS!
Tests: 1, Assertions: 0, Errors: 1.

所以,似乎 \Cake\ORM\TableRegistry::get() 搜索 default 连接。为什么?如何解决?


编辑

phpunit.xml.dist 在这里:

<?xml version="1.0" encoding="UTF-8"?>
<phpunit
    colors="true"
    processIsolation="false"
    stopOnFailure="false"
    syntaxCheck="false"
    bootstrap="./tests/bootstrap.php"
    >

    <testsuites>
        <testsuite name="cakephp-mysql-backup Test Cases">
            <directory>./tests/TestCase</directory>
        </testsuite>
    </testsuites>

    <!-- configure code coverage -->
    <filter>
        <whitelist>
            <directory suffix=".php">./src/</directory>
        </whitelist>
    </filter>
</phpunit>

异常由 运行 phpunitphpunit tests/TestCase/Utility/BackupExportTest.php 通过 nix 终端抛出。 phpunit/usr/bin/phpunit 上并通过 deb 包安装。

通常你最好将 PHPUnit 作为依赖项并通过 vendor/bin/phpunit 运行 它,但实际问题很可能是你没有配置 fixture 侦听器。

引自文档:

Before you can use fixtures you should double check that your phpunit.xml contains the fixture listener:

<!-- Setup a listener for fixtures -->
<listeners>
        <listener
        class="\Cake\TestSuite\Fixture\FixtureInjector"
        file="./vendor/cakephp/cakephp/src/TestSuite/Fixture/FixtureInjector.php">
                <arguments>
                        <object class="\Cake\TestSuite\Fixture\FixtureManager" />
                </arguments>
        </listener>
</listeners>

fixture 管理器负责创建正确的连接别名,即将非测试连接请求映射到 test* 连接,例如 defaulttest

另见