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

Laravel HTTP Test - Make sure JSON response has specific value in array

我有一个 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 的最佳方法是什么?

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

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);
}