【问题标题】:Laravel HTTP Test - Make sure JSON response has specific value in arrayLaravel HTTP 测试 - 确保 JSON 响应在数组中具有特定值
【发布时间】:2020-12-29 18:07:41
【问题描述】:

我有一个正在为其编写测试的 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 的最佳方法是什么?

【问题讨论】:

    标签: php laravel phpunit


    【解决方案1】:

    因为您要声明一个包含通配符的路径,所以您将获得每个匹配项的值(此函数在后台使用 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);
    }
    

    【讨论】:

      猜你喜欢
      • 2016-09-14
      • 1970-01-01
      • 2021-09-02
      • 2021-06-04
      • 2021-01-02
      • 2019-02-19
      • 2022-01-20
      • 2021-02-04
      • 1970-01-01
      相关资源
      最近更新 更多