2012-03-02 111 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));