我想使用 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/