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

标签 php mocking phpunit

我想使用 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();
  }

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

最佳答案

您需要使用任何 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:如何测试方法的调用顺序不正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15712777/

相关文章:

php - 如何在共享主机 (CPanel) 上的 Laravel 中分派(dispatch)排队作业

java - jsonpath : No value for JSON path: $. id,异常: Path 'id' is being applied to an array. 数组不能有属性

c# - 如何使 FakeItEasy 伪造对象的方法在第一次调用时抛出并在第二次调用时返回?

php - 网比 : phpUNit or SimpleTest?

laravel - 如何为 Laravel 更新密码表单编写测试?

PHPUnit数据库测试异常

php - Doctrine 的多对多自引用和互惠

php - 将平面数组拆分为包含输入数组中连续键值的分组子数组

php - 收件箱/消息数据模型

java - 每次使用 PowerMock 进行测试后,模拟行为都会重置