2012-06-22 18 views
5

शायद मैं यह गलत कर रहा हूं।मॉडल परीक्षण मामले में नकली कैसे बनाएं

मैं मॉडल (एंटीबॉडी) की पहले सेव विधि का परीक्षण करना चाहता हूं। इस विधि का एक हिस्सा संबंधित मॉडल (प्रजातियों) पर एक विधि को कॉल करता है। मैं प्रजाति मॉडल का नकल करना चाहता हूं लेकिन कैसे नहीं मिला।

क्या यह संभव है या मैं एमवीसी पैटर्न के खिलाफ कुछ ऐसा कर रहा हूं और इस तरह कुछ ऐसा करने की कोशिश कर रहा हूं जो मुझे नहीं करना चाहिए?

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 कर सकते हैं कुछ ऐसा करें:

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

अच्छा, यह आपकी 'प्रजाति' वस्तु को इंजेक्शन देने के तरीके पर निर्भर करता है। क्या यह निर्माता के माध्यम से इंजेक्शन दिया गया है? एक सेटर के माध्यम से? क्या यह विरासत में मिला है?

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