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

时间:2016-11-07 12:34:47

标签: cakephp testing phpunit cakephp-3.0

我按照here描述的方式使用灯具编写测试。

我的测试引导程序:

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>

通过nix终端运行phpunitphpunit tests/TestCase/Utility/BackupExportTest.php会引发异常。 phpunit位于/usr/bin/phpunit,并通过deb包发送。

1 个答案:

答案 0 :(得分:1)

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

来自文档的引用:

  

在您使用灯具之前,您应该仔细检查您的灯具   phpunit.xml包含fixture侦听器:

<!-- 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>

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

另见