2012-03-02 9 views
11

PHPUnit का उपयोग करके, मुझे आश्चर्य है कि अगर किसी विधि को अपेक्षित पैरामीटर के साथ कॉल किया जाता है, तो और लौटाए गए मान के साथ हम ऑब्जेक्ट का नकल कर सकते हैं?PHPunit: एक विधि का नकल कैसे करें जिसमें पैरामीटर है और एक लौटा हुआ मूल्य

doc में, वहाँ से गुजर पैरामीटर या दिए गए मान के साथ उदाहरण हैं, पर नहीं दोनों ...

मैं इस उपयोग करने की कोशिश:

 
// My object to test 
$hoard = new Hoard(); 
// Mock objects used as parameters 
$item = $this->getMock('Item'); 
$user = $this->getMock('User', array('removeItem')); 
... 
$user->expects($this->once()) 
    ->method('removeItem') 
    ->with($this->equalTo($item)); 
$this->assertTrue($hoard->removeItemFromUser($item, $user)); 

मेरे दावे विफल रहता है क्योंकि ढेर :: removeItemFromUser() को उपयोगकर्ता :: removeItem() के लौटाए गए मान को वापस करना चाहिए, जो सत्य है।

 
$user->expects($this->once()) 
    ->method('removeItem') 
    ->with($this->equalTo($item), $this->returnValue(true)); 
$this->assertTrue($hoard->removeItemFromUser($item, $user)); 

इसके अलावा निम्न संदेश के साथ विफल रहता है: "पैरामीटर मंगलाचरण उपयोगकर्ता के लिए गिनती :: removeItem (Mock_Item_767aa2db वस्तु (...)) बहुत कम है।"

 
$user->expects($this->once()) 
    ->method('removeItem') 
    ->with($this->equalTo($item)) 
    ->with($this->returnValue(true)); 
$this->assertTrue($hoard->removeItemFromUser($item, $user)); 

इसके अलावा के साथ विफल निम्नलिखित संदेश: "PHPUnit_Framework_Exception: पैरामीटर matcher पहले से ही परिभाषित किया गया है,"

इस विधि का सही ढंग से परीक्षण करने के लिए मुझे क्या करना चाहिए।

उत्तर

18

returnValue और दोस्तों के लिए with के बजाय आपको will का उपयोग करने की आवश्यकता है।

$user->expects($this->once()) 
    ->method('removeItem') 
    ->with($item) // equalTo() is the default; save some keystrokes 
    ->will($this->returnValue(true)); // <-- will instead of with 
$this->assertTrue($hoard->removeItemFromUser($item, $user)); 
संबंधित मुद्दे