如何在没有夹具的Yii PHPUnit测试中创建Model对象?

phy*_*ion 5 php phpunit object fixtures yii

我正在为我的Yii应用程序编写PHPUnit测试.我在这里读到:

提示:拥有太多夹具文件可能会大大增加测试时间.因此,您应该只为那些内容可能在测试期间发生变化的表提供fixture文件.用作查找的表不会更改,因此不需要fixture文件.

我确实有一个大型灯具(180条记录,加载时间大于20秒),仅用作查找.但是,我确实需要将它从关联数组轻松转换为Model对象,就像您通常可以使用下面的fixture语法一样.该提示表明,还有一种方法可以在不使用夹具的情况下创建Model对象,但是没有提到如何完成.任何人都可以帮忙吗?

使用fixture创建Model对象:

// tests/fixtures/Order.php
return array(
    'row_id' => array(
        'id' => 1,
        'name' => 'hello',
    )
)

// tests/unit/AbcTest.php
public $fixtures = array(
    'orders' => 'Order',
)

public test_abc()
{
    $order = $this->orders('row_id');
    ....
}
Run Code Online (Sandbox Code Playgroud)

Vla*_*pak 3

另一个选择:
当您创建数据库迁移时,您应该将其应用于生产数据库和测试数据库,而且您应该使用测试数据填充测试表。

这种方法的好处:

  1. 您将只运行一次填充 sql(不像固定装置 - 每次调用测试)。
  2. 您的测试将执行得很快,因为数据库将做好准备。
  3. 当您提交需要使用数据库中的新数据进行新测试的新功能时,您创建数据库迁移,并且它将以显式方式仅执行一次。

例如:

<?php

class m150608_110143_init extends CDbMigration
{
    public function safeUp()
    {
        $sql1 = "
            CREATE TABLE brand (
                id INT AUTO_INCREMENT,
                name VARCHAR(100) NOT NULL DEFAULT '',
                country VARCHAR(50) NOT NULL DEFAULT '',
                PRIMARY KEY (id)
            );
        ";
        $sql2 = "
            INSERT INTO brand VALUES
                (null, 'aston martin', 'UK'),
                (null, 'audi', 'Germany'),
                (null, 'bmw', 'Germany'),
                (null, 'citroen', 'France'),
                (null, 'peugeot', 'France'),
                (null, 'porsche', 'Germany'),
                (null, 'toyota', 'Japan'),
                (null, 'ferrari', 'Italy')
            ;
        ";
        // Production db.
        $this->setDbConnection(Yii::app()->db);
        $this->execute($sql1);
        // Test db.
        $this->setDbConnection(Yii::app()->dbUnitTest);
        $this->execute($sql1);
        // Populate test db with fixtures.
        $this->execute($sql2);
        return true;
    }

    public function down()
    {
        $sql = 'DROP TABLE brand;';
        // Test db.
        $this->setDbConnection(Yii::app()->dbUnitTest);
        $this->execute($sql);
        // Production db.
        $this->setDbConnection(Yii::app()->db);
        $this->execute($sql);
        return true;
    }
}
Run Code Online (Sandbox Code Playgroud)

并且在测试中您不必考虑固定装置。