2012-06-22 98 views
5

也许我做错了。如何在模型测试用例中创建模拟

我想测试模型(Antibody)的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; 
    } 
} 

回答

5

假设你的物种模型由蛋糕创建的关系,你可以si mply做这样的事情:

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*/)); 
} 
+0

谢谢你,那正是我一直在寻找的东西 – kaklon

0

那么,它取决于你的'物种'对象被注入的方式。 它是通过构造函数注入的吗?通过二传手?它是继承的吗?

这里是一个构造函数注入对象的例子:

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()); 
} 

的过程是相当有二传手注射对象相同:

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()); 
} 
相关问题