2012-06-22 3 views
5

아마도 내가 잘못하고 있습니다.모델 테스트 케이스에서 모의를 만드는 방법

모델 (Antibody)의 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; 
    } 
} 

답변

5

종 모델이 관계로 인해 케이크로 작성되었다고 가정하면 다음과 같이 할 수 있습니다. 다음과 같이하십시오 :

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

음, 'Species'개체가 주입되는 방식에 따라 다릅니다. 생성자를 통해 주입 되었습니까? 세터를 통해? 그것은 물려 받습니까?

이 과정은 세터 주입 객체와 매우 동일
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()); 
} 

:

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(); 
    $foo->setBar($barStub); 
    $this->assertFalse($foo->foo()); 
} 
관련 문제