如何在 PHPUnit 模拟对象中测试第二个参数

2022-08-30 08:48:02

这就是我所拥有的:

$observer = $this->getMock('SomeObserverClass', array('method'));
$observer->expects($this->once())
         ->method('method')
         ->with($this->equalTo($arg1));

但该方法应采用两个参数。我只是在测试第一个参数是否正确传递(如$arg 1)。

如何测试第二个参数?


答案 1

我相信做到这一点的方法是:

$observer->expects($this->once())
     ->method('method')
     ->with($this->equalTo($arg1),$this->equalTo($arg2));

$observer->expects($this->once())
     ->method('method')
     ->with($arg1, $arg2);

如果需要在 2nd arg 上执行不同类型的断言,也可以执行此操作:

$observer->expects($this->once())
     ->method('method')
     ->with($this->equalTo($arg1),$this->stringContains('some_string'));

如果需要确保某些参数传递多个断言,请使用 logicalAnd()

$observer->expects($this->once())
     ->method('method')
     ->with($this->logicalAnd($this->stringContains('a'), $this->stringContains('b')));

答案 2

推荐