在多次使用相同方法的情况下,应在代码中执行时使用“at”声明以及适当的计数。这样PHPUnit就知道你的意思,并且可以正确地完成期望/断言。
下面是一个普通的例子,其中法“跑”被多次使用:
public function testRunUsingAt()
{
$test = $this->getMock('Dummy');
$test->expects($this->at(0))
->method('run')
->with('f', 'o', 'o')
->will($this->returnValue('first'));
$test->expects($this->at(1))
->method('run')
->with('b', 'a', 'r')
->will($this->returnValue('second'));
$test->expects($this->at(2))
->method('run')
->with('l', 'o', 'l')
->will($this->returnValue('third'));
$this->assertEquals($test->run('f', 'o', 'o'), 'first');
$this->assertEquals($test->run('b', 'a', 'r'), 'second');
$this->assertEquals($test->run('l', 'o', 'l'), 'third');
}
我认为这是你在找什么,但如果我误解,请让我知道。
现在就嘲笑任何事情而言,您可以随意多次嘲笑它,但是您不想嘲笑它与设置中的名称相同,否则每次使用它时都会引用到设置。如果你需要在不同的场景中测试类似的方法,那么为每个测试进行模拟。您可以在设置中创建一个模拟,但是对于一次测试,在单个测试中使用不同的模拟类似项目,但不是全局名称。在use
声明
$one_of_many_methods_return = true;
$my_mock->expects($this->any())
->method('one_of_many_methods')
->will(
$this->returnCallback(
function() use (&$one_of_many_methods_return) {
return $one_of_many_methods_return;
}
)
);
$this->assertTrue($my_mock->one_of_many_methods());
$one_of_many_methods_return = false;
$this->assertFalse($my_mock->one_of_many_methods());
注意&
:
AFAIK不幸的是,phpunit没有这种可能性。你可以使用例如$ my_mock - > __ phpunit_hasMatchers(),但它不完全是你想要的。当然你可以用a)“at”匹配器或b)“returnCallback”在同一个方法上设置不同的返回值,但它们依赖于a)调用顺序b)调用参数..但也不是你要找的。我会让你知道我找出新的东西。 – Cyprian
另请参阅http://stackoverflow.com/questions/5484602/mock-in-phpunit-multiple-configuration-of-the-same-method-with-different-argum/5484864#5484864 – bishop