在集成测试中使用fixture


Use fixtures in integration tests

我发现CakePhp 3在集成测试中使用真实的db连接,所以像$this->post('articles/delete/1')这样的行删除真实的db行,即使提供了fixture。是否可以只使用装置(测试连接)提供的数据?模型测试与使用测试连接的夹具正常工作。

CakePHP在基于fixture的测试用例过程中执行以下操作:

1. Creates tables for each of the fixtures needed.
2. Populates tables with data, if data is provided in fixture.
3. Runs test methods.
4. Empties the fixture tables.
5. Removes fixture tables from database.

因此,正如在cake的文档中提到的,cakephp清空fixture表,无论是删除记录还是保存记录或做任何其他操作。

我找到问题的原因了。

在我的bootstrap.php中,我将事件监听器绑定到应用程序事件。在侦听器的构造函数中,我使用TableRegistry::get()初始化了模型对象的属性。

原因是TableRegistry将记住第一次调用时使用的连接,因此ConnectionManager::alias()将不起作用。由于我在事件的构造函数中初始化了TableRegistry,它在主应用程序加载和fixtureManager添加连接别名之前被调用。

所以千万不要在app加载前调用TableRegistry,否则可能会导致问题