PHPunit:如何模拟具有参数和返回值的方法

PHPunit:如何模拟具有参数和返回值的方法,php,unit-testing,phpunit,Php,Unit Testing,Phpunit,使用PHPUnit,我想知道我们是否可以模拟一个对象来测试一个方法是否使用一个期望的参数和一个返回值来调用 在中,有传递参数或返回值的示例,但不同时传递参数和返回值 我试着用这个: // My object to test $hoard = new Hoard(); // Mock objects used as parameters $item = $this->getMock('Item'); $user = $this->getMock('User', array('removeItem'

使用PHPUnit,我想知道我们是否可以模拟一个对象来测试一个方法是否使用一个期望的参数和一个返回值来调用

在中,有传递参数或返回值的示例,但不同时传递参数和返回值

我试着用这个:

// 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)); //我的测试对象 $窖藏=新窖藏(); //用作参数的模拟对象 $item=$this->getMock('item'); $user=$this->getMock('user',array('removietem'); ... $user->expected($this->once()) ->方法('removeItem') ->使用($this->equalTo($item)); $this->assertTrue($stage->removitemfromuser($item,$user)); 我的断言失败,因为囤积::removeItemFromUser()应该返回User::removeItem()的返回值,这是真的

$user->expects($this->once()) ->method('removeItem') ->with($this->equalTo($item), $this->returnValue(true)); $this->assertTrue($hoard->removeItemFromUser($item, $user)); $user->expected($this->once()) ->方法('removeItem') ->使用($this->equalTo($item),$this->returnValue(true)); $this->assertTrue($stage->removitemfromuser($item,$user)); 还出现以下消息时失败:“调用用户::removeItem(Mock_Item_767aa2db对象(…)的参数计数过低。

$user->expected($this->once()) ->方法('removeItem') ->使用($this->equalTo($item)) ->使用($this->returnValue(true)); $this->assertTrue($stage->removitemfromuser($item,$user)); 也会失败,并显示以下消息:“PHPUnit\u Framework\u异常:参数匹配器已定义,无法重新定义”


如何正确测试此方法。

对于
返回值
和朋友,您需要使用
will
而不是
with

$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));
$user->expected($this->once())
->方法('removeItem')
->with($item)//equalTo()是默认值;保存一些击键
->威尔($this->returnValue(true));//assertTrue($CADGE->removeItemFromUser($item,$user));

我知道这是一篇老文章,但它在搜索PHPUnit warning时位于顶部。方法名称匹配器已经定义,无法重新定义,所以我也会回答

这种警告信息还有其他原因。如果您这样描述链接方法中的模拟行为:

$research = $this->createMock(Research::class);
$research->expects($this->any())
    ->method('getId')
    ->willReturn(1)
    ->method('getAgent')
    ->willReturn(1);
您将得到警告方法名称匹配器已定义,无法重新定义。只需将其拆分为单独的语句,警告就会消失(在PHPUnit 7.5和8.3上测试)

$research = $this->createMock(Research::class);
$research->expects($this->any())
    ->method('getId')
    ->willReturn(1)
    ->method('getAgent')
    ->willReturn(1);
$research = $this->createMock(Research::class);

$research->expects($this->any())
    ->method('getId')
    ->willReturn(1);

$research->expects($this->any())
    ->method('getAgent')
    ->willReturn(1);