【问题标题】:In PHPUnit, how do I indicate different with() on successive calls to a mocked method?在 PHPUnit 中,如何在对模拟方法的连续调用中指示不同的 with()?
【发布时间】:2011-08-15 19:56:02
【问题描述】:

我想用不同的预期参数调用我的模拟方法两次。这不起作用,因为expects($this->once()) 在第二次调用时会失败。

$mock->expects($this->once())
     ->method('foo')
     ->with('someValue');

$mock->expects($this->once())
     ->method('foo')
     ->with('anotherValue');

$mock->foo('someValue');
$mock->foo('anotherValue');

我也试过了:

$mock->expects($this->exactly(2))
     ->method('foo')
     ->with('someValue');

但是如何添加 with() 来匹配第二次调用?

【问题讨论】:

标签: php mocking phpunit


【解决方案1】:

你需要使用at():

$mock->expects($this->at(0))
     ->method('foo')
     ->with('someValue');

$mock->expects($this->at(1))
     ->method('foo')
     ->with('anotherValue');

$mock->foo('someValue');
$mock->foo('anotherValue');

请注意,传递给at() 的索引适用于对同一模拟对象的所有方法调用。如果第二个方法调用是bar(),您不会将参数更改为at()

【讨论】:

  • 意识到这是一个老回复,在最近的PHPUnit版本中,at()方法已被官方弃用,所以withConsecutive()应该继续使用。
【解决方案2】:

引用自the answer from a similar question

从 PHPUnit 4.1 开始,您可以使用 withConsecutive 例如。

$mock->expects($this->exactly(2))
     ->method('set')
     ->withConsecutive(
         [$this->equalTo('foo'), $this->greaterThan(0)],
         [$this->equalTo('bar'), $this->greaterThan(0)]
       );

如果你想让它在连续调用时返回:

  $mock->method('set')
         ->withConsecutive([$argA1, $argA2], [$argB1], [$argC1, $argC2])
         ->willReturnOnConsecutiveCalls($retValueA, $retValueB, $retValueC);

如果可以避免使用at(),则不理想,因为as their docs claim

at() 匹配器的 $index 参数是指索引,从零开始,在给定模拟对象的所有方法调用中。使用此匹配器时要小心,因为它可能会导致与特定实现细节过于紧密相关的脆弱测试。

【讨论】:

猜你喜欢
  • 2013-09-12
  • 2010-09-25
  • 1970-01-01
  • 2013-05-30
  • 2011-11-06
  • 2020-11-15
  • 2016-09-29
  • 2022-08-22
  • 2019-08-07
相关资源
最近更新 更多