kak*_*lon 5 phpunit unit-testing cakephp mocking cakephp-2.1
也许我做错了.
我想测试一个模型(抗体)的beforeSave方法.此方法的一部分调用关联模型(Species)上的方法.我想嘲笑物种模型,但不知道如何.
是可能还是我做的事情违背了MVC模式,从而尝试做一些我不应该做的事情?
class Antibody extends AppModel {
public function beforeSave() {
// some processing ...
// retreive species_id based on the input
$this->data['Antibody']['species_id']
= isset($this->data['Species']['name'])
? $this->Species->getIdByName($this->data['Species']['name'])
: null;
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
假设您的Species模型由于关系而由cake创建,您可以简单地执行以下操作:
public function setUp()
{
parent::setUp();
$this->Antibody = ClassRegistry::init('Antibody');
$this->Antibody->Species = $this->getMock('Species');
// now you can set your expectations here
$this->Antibody->Species->expects($this->any())
->method('getIdByName')
->will($this->returnValue(/*your value here*/));
}
public function testBeforeFilter()
{
// or here
$this->Antibody->Species->expects($this->once())
->method('getIdByName')
->will($this->returnValue(/*your value here*/));
}
Run Code Online (Sandbox Code Playgroud)