我正在尝试通过使用PHPUnit
和Mock
函数来运行单元测试。我期望结果是一个数组。但是总是得到一个对象,而这个对象与我调用的函数无关。我该如何进行这项工作?
在下面提供我的代码
public function testGet()
{
$mock = $this->createMock(Category::class);
$map = [
[1, 2],
[3, 4],
];
$mock->method('get')
->willReturn($this->returnValueMap($map));
$testVal = $mock->get(1);
echo '<pre>';
print_r($testVal);
die;
}
我从印刷品中得到的结果是
PHPUnit\Framework\MockObject\Stub\ReturnValueMap Object ( [valueMap:PHPUnit\Framework\MockObject\Stub\ReturnValueMap:private] => Array ( [0] => Array ( [0] => 1 [1] => 2 )[1] => Array ( [0] => 3 [1] => 4 ) ) )
I am expecting to get 2 if I pass 1 to the function and expecting to get 4 if I pass 3 to the function.
The function which I want to test is
public function get(int $id) { $categoryData = new CategoryData(); $fields = ['name', 'gid']; $getCat = $categoryData->get($id, $fields); if ($getCat) { return $getCat; } return []; }
我在这里错过了什么吗?请帮助
答案 0 :(得分:1)
请尝试使用->will(
而不是->willReturn(
,因此Phpunit不会返回地图对象(willReturn
会逐字返回参数),而是对其进行进一步处理。
参考: