Laravel HTTP测试-确保JSON响应在数组中具有特定值



我有一个Laravel 8应用程序正在为其编写测试。以下是我的数据:

{
"data": [
{
"name": "Cumque ex quos.",
"createdAt": "2020-12-29T17:15:32.000000Z",
"updatedAt": "2020-12-29T17:15:32.000000Z",
"startAt": "2021-01-18 17:15:32",
"endAt": "2021-01-18 17:15:32",
"startedAt": null,
"status": "Running",
"range": {
"type": "percentage",
"max": 0,
"min": 0
},
},
{
"name": "Cumque ex quos 2.",
"createdAt": "2020-12-29T17:15:32.000000Z",
"updatedAt": "2020-12-29T17:15:32.000000Z",
"startAt": "2021-01-18 17:15:32",
"endAt": "2021-01-18 17:15:32",
"startedAt": null,
"status": "Running",
"range": {
"type": "percentage",
"max": 20,
"min": 100
},
},
],
"other_keys" [ ... ];
}

我想测试响应中status的每个值是否等于Running的值。以下是我的测试:

/** @test */
public function should_only_return_data_that_are_running()
{
$response = $this->getJson('/api/v2/data');
$response->assertJsonPath('data.*.status', 'Running');
}

出现以下情况时失败:

Failed asserting that Array &0 (
0 => 'Running'
1 => 'Running'
) is identical to 'Running'.

我显然测试得不对。测试data数组中返回的所有对象并确保status值等于Running的最佳方法是什么?

因为您正在断言一个包含通配符的路径,所以您将获得每个匹配项的值(此函数在后台使用data_get()辅助对象。(您需要构建一个具有相同数量元素的结构。可能是这样的:

public function should_only_return_data_that_are_running()
{
$response = $this->getJson('/api/v2/data');
$test = array_fill(0, count($response->data), 'Running');
$response->assertJsonPath('data.*.status', $test);
}

最新更新