PHPUnit:如何测试方法的调用顺序是否不正确?
我想使用PHPUnit测试方法的调用顺序是否正确 我的第一次尝试是在模拟对象上使用PHPUnit:如何测试方法的调用顺序是否不正确?,php,mocking,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');
->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();
}
有没有更优雅的方法?谢谢 您需要使用任何
调用mocker
来实现您的期望。例如,这应该起作用:
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();
}
请看,我认为这会有所帮助,但我不确定。该页面似乎表明,
->at()
如果在不同的索引处调用其方法,则不会导致失败,我的第一个测试用例已经证明了这一点。你在那页上还有什么有用的想法吗?我想你可以在某种程度上使用at
和verify
的组合。除了在我的phpunit版本中“Mocked method not existence”失败之外,这是可行的!令人惊叹的!这适用于PHPUnit 9.5.0,但会引发一个警告:at()匹配器已被弃用。它将在PHPUnit 10中移除。请重构测试,使其不依赖于调用方法的顺序。