我有一个 PHPUnit 模拟对象,它返回 'return value'
无论它的参数是什么:
// From inside a test...
$mock = $this->getMock('myObject', 'methodToMock');
$mock->expects($this->any))
->method('methodToMock')
->will($this->returnValue('return value'));
我希望能够根据传递给模拟方法的参数返回不同的值。我尝试过类似的方法:
$mock = $this->getMock('myObject', 'methodToMock');
// methodToMock('one')
$mock->expects($this->any))
->method('methodToMock')
->with($this->equalTo('one'))
->will($this->returnValue('method called with argument "one"'));
// methodToMock('two')
$mock->expects($this->any))
->method('methodToMock')
->with($this->equalTo('two'))
->will($this->returnValue('method called with argument "two"'));
但是如果没有使用参数 'two'
调用 mock,这会导致 PHPUnit 提示,所以我假设 methodToMock('two')
的定义覆盖第一个的定义。
所以我的问题是:有没有办法让 PHPUnit 模拟对象根据其参数返回不同的值?如果有,怎么做?
最佳答案
使用回调。例如(直接来自 PHPUnit 文档):
<?php
class StubTest extends PHPUnit_Framework_TestCase
{
public function testReturnCallbackStub()
{
$stub = $this->getMock(
'SomeClass', array('doSomething')
);
$stub->expects($this->any())
->method('doSomething')
->will($this->returnCallback('callback'));
// $stub->doSomething() returns callback(...)
}
}
function callback() {
$args = func_get_args();
// ...
}
?>
在 callback() 中做任何你想做的处理,并根据你的 $args 适本地返回结果。
关于php - 如何让 PHPUnit MockObjects 根据参数返回不同的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/277914/