PHPUnit:如何使用多个参数模拟多个方法调用?
我正在为使用 PHPUnit 的方法编写单元测试.我正在测试的方法在同一个对象上调用相同的方法 3 次,但使用不同的参数集.我的问题类似于提出的问题 这里和这里
I am writing a unit test for a method using PHPUnit. The method I am testing makes a call to the same method on the same object 3 times but with different sets of arguments. My question is similar to the questions asked here and here
其他帖子中提出的问题与只接受一个参数的模拟方法有关.
The questions asked in the other posts have to do with mocking methods that only take one argument.
但是,我的方法需要多个参数,我需要这样的东西:
However, my method takes multiple arguments and I need something like this:
$mock->expects($this->exactly(3))
->method('MyMockedMethod')
->with(
$this->logicalOr(
$this->equalTo($arg1, $arg2, arg3....argNb),
$this->equalTo($arg1b, $arg2b, arg3b....argNb),
$this->equalTo($arg1c, $arg2c, arg3c....argNc)
)
);
此代码不起作用,因为 equalTo()
仅验证一个参数.给它多个参数会引发异常:
This code doesn't work because equalTo()
validates only one argument. Giving it more than one argument throws an exception:
PHPUnit_Framework_Constraint_IsEqual::__construct() 的参数 #2 必须是数字
Argument #2 of PHPUnit_Framework_Constraint_IsEqual::__construct() must be a numeric
有没有办法为具有多个参数的方法进行 logicalOr
模拟?
Is there a way to do a logicalOr
mocking for a method with more than one argument?
提前致谢.
推荐答案
在我的例子中,答案很简单:
In my case the answer turned out to be quite simple:
$this->expects($this->at(0))
->method('write')
->with(/* first set of params */);
$this->expects($this->at(1))
->method('write')
->with(/* second set of params */);
关键是使用$this->at(n)
,其中n
是方法的第N次调用.我尝试过的任何 logicalOr()
变体都无法执行任何操作.
The key is to use $this->at(n)
, with n
being the Nth call of the method. I couldn't do anything with any of the logicalOr()
variants I tried.
相关文章