如何测试关系的比例?

时间:2016-06-20 15:45:06

标签: php unit-testing activerecord yii2

我为班级workAbroads的班级WorkTypeworkType关系声明了WorkAbroad关系:

class WorkType extends \yii\db\ActiveRecord
{
    ...

    public function getWorkAbroads()
    {
        return $this->hasMany(WorkAbroad::className(), ['WorkTypeID' => 'ID']);
    }
}

class WorkAbroad extends \yii\db\ActiveRecord
{
    ...

    public function getWorkType()
    {
        return $this->hasOne(WorkType::className(), ['ID' => 'WorkTypeID']);
    }
}

我想测试这种关系的比例。怎么做得好?

假设我创建了一个$workType个对象和一百个$workAbroads个对象。

我希望以下表达式将返回$workAboards个对象的数组:

$workAboards = $workType->getWorkAbroads(); // The SQL query is always executed
// $workAboards = $workType->workAbroads; // The SQL query will be executed once

然后检查成功:

assertEquals(100, count($workAbroads));

相反,我收到以下错误:

Failed asserting that 1 matches expected 100

我知道我可以通过查询以下为真的所有ActiveRecord对象WorkAbroad来测试关系:

'WorkTypeID' => $workType->ID

但我想了解为什么第一种方法不起作用?..

我将非常感谢这些信息。谢谢大家。

1 个答案:

答案 0 :(得分:1)

$workType->getWorkAbroads()将返回ActiveQuery个对象,而不是WorkAbroad个对象的数组,您应该尝试:

$workAboards = $workType->getWorkAbroads()->all();

但是如果你只想计算相关记录,你应该使用它:

assertEquals(100, $workType->getWorkAbroads()->count());