2012-06-22 137 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()); 
} 
相關問題