简体   繁体   English

PHPUnit:如何测试方法调用顺序不正确?

[英]PHPUnit: how to test that methods are called in incorrect order?

I want to use PHPUnit to test that methods are called in the right order. 我想使用PHPUnit来测试以正确的顺序调用方法。

My first attempt, using ->at() on a mock object, did not work. 我在模拟对象上使用->at()第一次尝试不起作用。 For example, I expected the following to fail, but it does not: 例如,我预计以下内容会失败,但它不会:

  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();
  }      

The only way I could think of that forced a failure if things were called in the wrong order was something like this: 如果以错误的顺序调用事件,我能想到的唯一方法就是强制失败是这样的:

  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();
  }

Is there a more elegant way to do this? 有没有更优雅的方式来做到这一点? Thanks! 谢谢!

You need involve any InvocationMocker to make your expectations work. 您需要涉及任何InvocationMocker才能使您的期望有效。 For example this should work: 例如,这应该工作:

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();
}  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM