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

yvo*_*yer 13 php phpunit unit-testing

使用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));

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

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

也失败并显示以下消息:" 调用User :: removeItem(Mock_Item_767aa2db Object(...))的参数计数太低. "

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

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

我该怎么做才能正确测试这个方法.

Dav*_*ess 21

您需要使用will,而不是with用于returnValue和朋友.

$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));
Run Code Online (Sandbox Code Playgroud)


Vas*_*rov 6

我知道这是一个旧帖子,但它在搜索 PHPUnit 警告方法名称匹配器已定义,无法重新定义,所以我也会回答。

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

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

您将收到警告Method name matcher is already defined, cannot redefine。只需将其拆分为单独的语句,警告就会消失(在 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);
Run Code Online (Sandbox Code Playgroud)