PHPUnit将返回BackMap方法 - 回调参数

时间:2014-11-19 07:47:53

标签: php mocking phpunit

我的用例更复杂,但要保持简单:

class MockObject {
    public function test($param1, callable $callback = null) {
        return is_null($callback) ? $param1 : $callback($param1);
    }
}

我想使用returnMap为我的其他测试模拟这个类。

$map = [
    ['a', null, 'a'],
    ['b', $WHAT_SHOULD_BE_HERE?, 'b']
];

$mock = $this->getMock('MockObject');
$mock->expects($this->atLeastOnce())->method('test')->willReturnMap($map);

$this->assertEquals('a', $mock->test('a')); // Works 
$this->assertEquals('b', $mock->test('b', function($value){return $value})); // Doesn't work 

1 个答案:

答案 0 :(得分:3)

只需定义一个$callback并在地图和断言中使用它:

$callback = function($value) { return $value; };

$map = [
    ['a', null, 'a'],
    ['b', $callback, 'b']
];

$mock = $this->getMock('MockObject');
$mock->expects($this->atLeastOnce())->method('test')->will($this->returnValueMap($map));

$this->assertEquals('a', $mock->test('a')); // Works 
$this->assertEquals('b', $mock->test('b', $callback)); // Should work

通过使用函数计算返回值,您可以更好地控制所有情况:

$mock = $this->getMock('MockObject');
$mock->expects($this->atLeastOnce())
     ->method('test')
     ->will($this->returnCallback(function($param1, $param2) {
          // return value depends on parameters
     }));