2012-03-02 11 views
11

PHPUnit kullanarak, bir yöntem beklenen bir parametre ve döndürülmüş bir değer ile deneniyor, sınamak için bir nesne alay edebilir miyim? doc yılındaPHPunit: Parametre VE döndürülen bir değer olan bir yöntem ile alay Nasıl

, orada geçen parametre veya iade değerle örnekleridir ama ...

Bunu kullanarak çalıştı hem:

 
// 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)); 

Benim iddiası çünkü istifliyorlar başarısız :: removeItemFromUser(), true olan User :: removeItem() öğesinin döndürülen değerini döndürmelidir.

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

Ayrıca aşağıdaki iletiyle başarısız: "Parametre çağırma Kullanıcı için saymak :: removeItem (Mock_Item_767aa2db Nesnesi (...)) çok düşük olduğu."

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

Ayrıca başarısız oluyor Aşağıdaki ileti: "PHPUnit_Framework_Exception: Parametre eşleştiricisi zaten tanımlı, yeniden tanımlayamıyor"

Bu yöntemi doğru şekilde test etmek için ne yapmalıyım?

cevap

18

returnValue ve arkadaşları için with yerine will kullanmanız gerekir.

$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)); 
İlgili konular