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