【问题标题】:PHPUnit: how to test that methods are called in incorrect order?PHPUnit:如何测试以错误的顺序调用方法?
【发布时间】:2013-05-01 08:13:57
【问题描述】:

我想使用 PHPUnit 来测试方法是否以正确的顺序被调用。

我的第一次尝试是在模拟对象上使用->at(),但没有成功。例如,我预计以下操作会失败,但事实并非如此:

  public function test_at_constraint()
  {
    $x = $this->getMock('FirstSecond', array('first', 'second'));
    $x->expects($this->at(0))->method('first');
    $x->expects($this->at(1))->method('second');

    $x->second();
    $x->first();
  }      

如果事情以错误的顺序调用,我能想到的唯一方法是这样的:

  public function test_at_constraint_with_exception()
  { 
    $x = $this->getMock('FirstSecond', array('first', 'second'));

    $x->expects($this->at(0))->method('first');
    $x->expects($this->at(1))->method('first')
      ->will($this->throwException(new Exception("called at wrong index")));

    $x->expects($this->at(1))->method('second');
    $x->expects($this->at(0))->method('second')
      ->will($this->throwException(new Exception("called at wrong index")));

    $x->second();
    $x->first();
  }

有没有更优雅的方法来做到这一点?谢谢!

【问题讨论】:

  • 我认为这会有所帮助,但我不确定。
  • 该页面似乎表明 ->at() 如果在不同的索引处调用其方法,则不会导致失败,我的第一个测试用例已经证明了这一点。您在该页面上还有什么其他有用的想法吗?
  • 我在想你可以以某种方式使用atverify 的组合。

标签: php mocking phpunit


【解决方案1】:

您需要参与任何InvocationMocker 才能实现您的期望。例如这应该有效:

public function test_at_constraint()
{
    $x = $this->getMock('FirstSecond', array('first', 'second'));
    $x->expects($this->at(0))->method('first')->with();
    $x->expects($this->at(1))->method('second')->with();

    $x->second();
    $x->first();
}  

【讨论】:

  • 除了在我的 phpunit 版本中它因“模拟方法不存在”而失败之外,这有效!太棒了!
  • 这适用于 PHPUnit 9.5.0 但会引发警告:at() 匹配器已被弃用。它将在 PHPUnit 10 中删除。请重构您的测试,使其不依赖于调用方法的顺序。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-12-18
  • 1970-01-01
  • 2015-09-25
  • 1970-01-01
  • 2015-03-20
  • 2018-06-28
  • 2014-05-15
相关资源
最近更新 更多