也许我做错了。
我想测试一个模型(抗体)的beforeSave方法。此方法的一部分调用关联模型(物种)上的方法。我很想模仿物种模型,但我不知道该怎么做。
有没有可能,或者我正在做一些违背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;
}
}发布于 2012-06-22 18:58:47
假设你的物种模型是由于关系而由蛋糕创建的,你可以简单地这样做:
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*/));
}发布于 2012-06-22 17:48:24
好吧,这取决于你的“物种”对象的注入方式。它是通过构造函数注入的吗?通过二传手?它是遗传的吗?
下面是一个包含构造函数注入对象的示例:
class Foo
{
/** @var Bar */
protected $bar;
public function __construct($bar)
{
$this->bar = $bar;
}
public function foo() {
if ($this->bar->isOk()) {
return true;
} else {
return false;
}
}
}那么你的测试应该是这样的:
public function test_foo()
{
$barStub = $this->getMock('Overblog\CommonBundle\TestUtils\Bar');
$barStub->expects($this->once())
->method('isOk')
->will($this->returnValue(false));
$foo = new Foo($barStub);
$this->assertFalse($foo->foo());
}这个过程与setter注入的对象非常相似:
public function test_foo()
{
$barStub = $this->getMock('Overblog\CommonBundle\TestUtils\Bar');
$barStub->expects($this->once())
->method('isOk')
->will($this->returnValue(false));
$foo = new Foo();
$foo->setBar($barStub);
$this->assertFalse($foo->foo());
}https://stackoverflow.com/questions/11152128
复制相似问题