2012-03-02 103 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()應該返回User :: 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:參數匹配器已定義,無法重新定義

我應該怎樣做才能正確測試此方法。

回答

18

您需要使用will而不是withreturnValue和朋友。

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