首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在模型测试用例中创建模拟

如何在模型测试用例中创建模拟
EN

Stack Overflow用户
提问于 2012-06-22 15:45:56
回答 2查看 3K关注 0票数 5

也许我做错了。

我想测试一个模型(抗体)的beforeSave方法。此方法的一部分调用关联模型(物种)上的方法。我很想模仿物种模型,但我不知道该怎么做。

有没有可能,或者我正在做一些违背MVC模式的事情,并因此尝试做一些我不应该做的事情?

代码语言:javascript
复制
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;
    }
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-06-22 18:58:47

假设你的物种模型是由于关系而由蛋糕创建的,你可以简单地这样做:

代码语言:javascript
复制
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*/));
}
票数 6
EN

Stack Overflow用户

发布于 2012-06-22 17:48:24

好吧,这取决于你的“物种”对象的注入方式。它是通过构造函数注入的吗?通过二传手?它是遗传的吗?

下面是一个包含构造函数注入对象的示例:

代码语言:javascript
复制
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;
        }
    }
}

那么你的测试应该是这样的:

代码语言:javascript
复制
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注入的对象非常相似:

代码语言:javascript
复制
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());
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11152128

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档