【发布时间】:2016-07-22 16:58:00
【问题描述】:
我正在运行 CakePHP 2.8.X,并且正在尝试为模型函数编写单元测试。
我们将模型称为Item,我正在尝试测试它的getStatus 方法。
但是,该模型在 getStatus 方法中调用其 find。
所以是这样的:
class Item extends Model
{
public function getStatus($id) {
// Calls our `$this->Item-find` method
$item = $this->find('first', [
'fields' => ['status'],
'conditions' => ['Item.id' => $id]
]);
$status = $item['status'];
$new_status = null;
// Some logic below sets `$new_status` based on `$status`
// ...
return $new_status;
}
}
设置“$new_status”的逻辑有点复杂,所以我想为它写一些测试。
但是,我不完全确定如何在 Item::getStatus 中覆盖 find 调用。
通常当我想模拟模型的函数时,我使用$this->getMock 和method('find')->will($this->returnValue($val_here)),但我不想完全模拟我的Item,因为我想测试它的实际getStatus 函数。
也就是说,在我的测试函数中,我将调用:
// This doesn't work since `$this->Item->getStatus` calls out to
// `$this->Item->find`, which my test suite doesn't know how to compute.
$returned_status = $this->Item->getStatus($id);
$this->assertEquals($expected_status, $returned_status);
那么我如何在我的测试中与我的真实Item 模型沟通,让它覆盖其对其find 方法的内部调用?
【问题讨论】:
标签: php unit-testing cakephp phpunit