Phpunit 断言不管调用顺序如何,给定的参数都会传递给方法
在测试方法A中,方法B被多次调用。我想断言,这些调用中至少有一个使用了特定的参数,但我不在乎何时调用 我如何构造一个PHPUnit测试来断言这一点 我在谷歌和StackOverflow上搜索了这个解决方案,但运气不好,而且这些文档也没有多大帮助 我已尝试使用此帮助器函数:Phpunit 断言不管调用顺序如何,给定的参数都会传递给方法,phpunit,Phpunit,在测试方法A中,方法B被多次调用。我想断言,这些调用中至少有一个使用了特定的参数,但我不在乎何时调用 我如何构造一个PHPUnit测试来断言这一点 我在谷歌和StackOverflow上搜索了这个解决方案,但运气不好,而且这些文档也没有多大帮助 我已尝试使用此帮助器函数: protected function expectAtLeastOnce( $Mock, $method, $args = array() ) { $ExpectantMock = $Mock->expects(
protected function expectAtLeastOnce( $Mock, $method, $args = array() ) {
$ExpectantMock = $Mock->expects( $this->atLeastOnce() )->method( $method );
$this->addWithArgsExpectation( $args, $ExpectantMock );
}
但是,这不起作用,因为它希望每个调用都使用指定的参数,即使它接受的调用数大于零
类似问题:
- -建议使用
,这需要了解调用顺序,因此不是解决方案->at()
- -未答复;评论建议使用测试框架,我对此不感兴趣
protected function assertMethodCallsMethodWithArgsAtAnyTime(
$InquisitiveMock,
$inquisitiveMethod,
$InitiatingObject,
$initiatingMethod,
$expectedArgs = array()
) {
$success = false;
$argsChecker = function () use ( &$success, $expectedArgs ) {
$actualArgs = func_get_args();
if (
count( $expectedArgs ) === count( $actualArgs )
&& $expectedArgs === $actualArgs
) {
$success = true;
}
};
$InquisitiveMock->expects( $this->any() )
->method( $inquisitiveMethod )
->will( $this->returnCallback( $argsChecker ) );
$InitiatingObject->$initiatingMethod();
$this->assertTrue( $success );
}
可能不是很优雅,但您可以使用回调手动检查方法参数,并在找到正确的参数时设置标志:
$mock = $this->getMock('Class', array('theMethod'));
$call_done = false;
$params_checker = function() use (&$call_done) {
$args = func_get_args();
if (1 == count($args) && "A" == $args[0]) {
$call_done = true;
}
};
$mock->expects($this->any())
->method('theMethod')
->will($this->returnCallback($params_checker));
$mock->theMethod("A");
$this->assertTrue($call_done);
谢谢你的回答!我去看看我能不能让它工作。你在第一行缺少括号吗?请原谅我的迟钝,但是
$sut
是从哪里来的?我的错,$sut应该是$mock。编辑过的againTook让我稍微适应一下我自己的需要,但是这个非常好用!非常感谢。