【问题标题】:Laravel HTTP Test using getJson + assertJsonStructure array of objectsLaravel HTTP 测试使用 getJson + assertJsonStructure 对象数组
【发布时间】:2021-04-06 07:42:21
【问题描述】:

我有一个 Laravel 8 应用程序,我想在其中测试从 HTTP API 调用返回的 JSON 的一部分。我的响应对象如下所示:

{
    "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": "Pending",
            "range": {
                "type": "percentage",
                "max": 20,
                "min": 100
            },
        },
    ],
    "other_keys" [ ... ];
}

我有兴趣测试data 键返回的数组的结构。这是我正在使用的测试失败:

 /** @test */
    public function should_get_data_and_validate_the_structure()
    {
        $this->withoutExceptionHandling();

        $response = $this->getJson('/api/v1/data');

        $response->assertJsonStructure([
            'data' => [
                'createdAt',
                'endAt',
                'name',
                'startAt',
                'startedAt',
                'status',
                'updatedAt',
                'range' => [
                    'max',
                    'min',
                    'type'
                ],           
            ]
        ]);
    }

测试失败并出现以下错误:Failed asserting that an array has the key 'createdAt'.

【问题讨论】:

    标签: php json laravel phpunit


    【解决方案1】:

    data 是一个array,因此,要断言嵌套对象的结构,我们需要使用* 通配符:

    $response->assertJsonStructure([
       'data' => [
             '*' => [
                'createdAt',
                'endAt',
                'name',
                'startAt',
                'startedAt',
                'status',
                'updatedAt',
                'range' => [
                    'max',
                    'min',
                    'type'
                ],
            ]
          ]
    ]);
    

    【讨论】:

    • 这行得通——你能指出我在文档中讨论通配符的位置吗?
    • 乐于助人!不确定它是否记录在案,但我已经直接检查了source code
    猜你喜欢
    • 1970-01-01
    • 2015-02-20
    • 2023-03-04
    • 2013-06-21
    • 2015-09-12
    • 2017-08-02
    • 2010-09-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多