【问题标题】:Cakephp 3 Test: How to load records from database?Cakephp 3 测试:如何从数据库中加载记录?
【发布时间】:2019-11-05 10:24:52
【问题描述】:

我需要测试一些报告,这些报告具有复杂的数据结构和大量数据影响,因此为此目的创建夹具将是一项非常乏味的工作。我想使用现有的数据库(实际上是它的副本)来测试报告。

如何在 cakephp 3 测试中实现这一点? 是否可以在 cakephp 3 中从数据库中加载夹具记录(不是表结构)?

【问题讨论】:

    标签: php cakephp testing cakephp-3.0


    【解决方案1】:

    您可以使用 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)
    

    例如:

    cake bake fixture you_table_name -r -n 100
    

    【讨论】:

    • 谢谢,但是有没有不使用fixture直接使用数据库的解决方案?我已经转储了“真实”数据库并为此创建了一个单独的数据库(测试报告),但是有很多记录(数千条),所以我认为从这些记录生成固定装置不是一个好主意。跨度>
    • 这也可能有助于某些人加载记录。 stackoverflow.com/a/33789238/711401
    【解决方案2】:

    由于 PHPUnit 会在每次测试之间删除它可以访问的数据库中的所有内容,因此您可能不想授予它访问生产数据库的权限。

    您正在寻找的解决方案可能是编写每个夹具的 init() 函数,以根据从生产数据库中提取的数据构建其 $records 属性。

    像这样(未验证):

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

    请注意,这确实会减慢您的测试速度,尽管缓存结果会缓解这种情况。

    【讨论】:

      猜你喜欢
      • 2013-12-28
      • 1970-01-01
      • 2012-04-24
      • 1970-01-01
      • 2012-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多