php - 使用 getJson + assertJsonStructure 对象数组的 Laravel HTTP 测试

标签 php json laravel phpunit

我有一个 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'
                ],           
            ]
        ]);
    }

测试失败并出现以下错误:断言数组具有键“createdAt”失败。

最佳答案

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

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

关于php - 使用 getJson + assertJsonStructure 对象数组的 Laravel HTTP 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65496183/

相关文章:

php - 我需要将多个动态字段值添加到 mysql 数据库中

php - Magento 商店 - 将 nofollow 添加到分层导航

php - 使用 postman 将文件发送到 Laravel API

laravel - PHPunit 未捕获错误:调用未定义的方法 PHPUnit_Util_Configuration::getTestdoxGroupConfiguration()

PHP进程贴json

php - Laravel 5 中的链接表

javascript - Bootstrap 模式中的动态内容和 Ajax [Laravel] 中的动态数据

php - 如何使用 PHP::PDO 执行带变量的 mysql 脚本?

javascript - 未定义元素从 URL 获取 JSON

json - 来自 JSON 请求的 Scala 对象