简体   繁体   English

Cakephp 3 测试:如何从数据库加载记录?

[英]Cakephp 3 Test: How to load records from database?

I need to test some reports, there is a complex data structure and a lot of data affect for those reports, so creating fixtures for this purpose would be very tedious work.我需要测试一些报告,这些报告有一个复杂的数据结构和很多数据影响,因此为此目的创建装置将是非常乏味的工作。 I'd like to use an existing database (actually copy of it) to test reports.我想使用现有的数据库(实际上是它的副本)来测试报告。

How can I achieve this in cakephp 3 tests?如何在 cakephp 3 测试中实现这一点? Is it possible to load records for fixtures (not a structure of table) from database in cakephp 3?是否可以从 cakephp 3 中的数据库加载夹具记录(不是表结构)?

You can create fixtures from existing records in your tables using the Bake utility:您可以使用Bake实用程序从表中的现有记录创建设备:

    --records, -r     Generate a fixture with records from the non-test
                      database. Used with --count and --conditions to limit
                      which records are added to the fixture.
    --count, -n       When using generated data, the number of records to
                      include in the fixture(s). (default:
                      1)

For example:例如:

cake bake fixture you_table_name -r -n 100

Since PHPUnit deletes everything from the database that it has access to between each test, you probably don't want to give it access to your production database.由于 PHPUnit 会在每次测试之间删除它有权访问的数据库中的所有内容,因此您可能不想让它访问您的生产数据库。

The solution you're looking for is probably writing each fixture's init() function to build its $records property from data it pulls from the production database.您正在寻找的解决方案可能是编写每个夹具的init()函数,以根据它从生产数据库中提取的数据构建其$records属性。

Like this (unverified):像这样(未经证实):

public function init()
{
    $thingsTable = TableRegistry::get('Things');
    $this->records = $thingsTable->find()->toArray();
    parent::init();
}

Note that this will really slow down your tests, though caching the results will mitigate that.请注意,这确实会减慢您的测试速度,尽管缓存结果会减轻这种影响。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM