PHPunit:如何模拟一个有参数AND返回值的方法


PHPunit: How to mock a method that has a parameter AND a returned value

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

在文档中,有一些例子传递了参数或返回值,但没有两者。。。

我试过使用这个:

//我要测试的对象$囤积=新囤积();//用作参数的模拟对象$item=$this->getMock('item');$user=$this->getMock('user',array('moveItem'));。。。$user->expects($this->once())->方法("删除项")->with($this->equalTo($item));$this->assertTrue($囤积->removeItemFromUser($item,$user));

我的断言失败,因为Hoard::removeItemFromUser()应该返回User::removeItem()的返回值,这是真的。

$user->expects($this->once())->方法("删除项")->with($this->equalTo($item),$this->returnValue(true));$this->assertTrue($囤积->removeItemFromUser($item,$user));

同样失败,并显示以下消息:"调用User::removeItem(Mock_Item_767aa2db Object(…))的参数计数过低。"

$user->expects($this->once())->方法("删除项")->with($this->equalTo($item))->with($this->returnValue(true));$this->assertTrue($囤积->removeItemFromUser($item,$user));

同样失败,并显示以下消息:"PHPUnit_Framework_Exception:参数匹配器已定义,无法重新定义"

我应该怎么做才能正确地测试这个方法。

对于returnValue和好友,您需要使用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));

我知道这是一篇旧文章,但它在搜索PHPUnit警告中名列前茅方法名称匹配器已经定义,无法重新定义,所以我也会回答。

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

$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);
$research->expects($this->any())
    ->method('getAgent')
    ->willReturn(1);