测试时的 CakePHP 连接

CakePHP connections while testing

我目前正在尝试对我的一些代码进行单元测试。我正在执行一些手动输入的 SQL 语句,如下所示:

$db = ConnectionManager::get('default');
...
$stmt = $db->prepare($sql);
$stmt->execute();

我假设每当我 运行 单元测试并请求 default 连接时,我将获得 test 连接。如果它没有在我的配置中定义,它将抛出异常。 当我 运行 一个针对数据库执行语句的测试时,它总是针对 default 连接执行。 test 连接从未使用过。

知道我做错了什么吗?

我的数据库配置如下:

'Datasources' => [
    'default' => [
        'className' => 'Cake\Database\Connection',
        'driver' => 'Cake\Database\Driver\Mysql',
        'persistent' => false,
        'host' => 'localhost',
        'username' => 'root',
        'password' => '',
        'database' => 'dbname',
        'encoding' => 'utf8',
        'timezone' => 'UTC',
        'cacheMetadata' => true,
        'quoteIdentifiers' => false,
    ],

    /**
     * The test connection is used during the test suite.
     */
    'test' => [
        'className' => 'Cake\Database\Connection',
        'driver' => 'Cake\Database\Driver\Mysql',
        'persistent' => false,
        'host' => 'localhost',
        'username' => 'root',
        'password' => '',
        'database' => 'dbname_test',
        'encoding' => 'utf8',
        'timezone' => 'UTC',
        'cacheMetadata' => true,
        'quoteIdentifiers' => false,
    ],
]

感谢您的帮助!

编辑 我认为文档有误:

By default CakePHP will alias each connection in your application. Each connection defined in your application’s bootstrap that does not start with test_ will have a test_ prefixed alias created. Aliasing connections ensures, you don’t accidentally use the wrong connection in test cases. Connection aliasing is transparent to the rest of your application. For example if you use the ‘default’ connection, instead you will get the test connection in test cases. If you use the ‘replica’ connection, the test suite will attempt to use ‘test_replica’.

Link

您可以在那里读到 CakePHP 在 运行 单元测试时自动将 default 连接别名为 test。要获得该行为,您必须自己在 phpunit bootstrap.php 中定义别名,如下所示:

\Cake\Datasource\ConnectionManager::alias('test', 'default');

你可以在这里阅读 ConnectionManager::alias 有趣的是 alias 的文档明确指出

For example, if you alias 'default' to 'test', fetching 'default' will always return the 'test' connection as long as the alias is defined.

当您在我们的 phpunit.xml 配置中加载设备管理器侦听器时,连接别名默认完成,因为它分布在应用程序模板中:

https://github.com/cakephp/app/blob/master/phpunit.xml.dist#L23-L31

我们也有同样的错误,对于某些表,测试无缘无故地获取默认数据库而不是测试数据库。最后使用 setUp 函数顶部的代码(在 parent::setUp() 之前)解决了问题(我们有一个主测试 class,我们从中扩展所有测试,进行一些设置。我们把它在那里)

TableRegistry::clear();