Laravel 使用 getJson + assertJsonStructure 对象数组的 HTTP 测试
Laravel HTTP Test using getJson + assertJsonStructure array of objects
我有一个 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'.
data
是一个 array
,因此,要声明嵌套对象的结构,我们需要使用 *
通配符:
$response->assertJsonStructure([
'data' => [
'*' => [
'createdAt',
'endAt',
'name',
'startAt',
'startedAt',
'status',
'updatedAt',
'range' => [
'max',
'min',
'type'
],
]
]
]);
我有一个 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'.
data
是一个 array
,因此,要声明嵌套对象的结构,我们需要使用 *
通配符:
$response->assertJsonStructure([
'data' => [
'*' => [
'createdAt',
'endAt',
'name',
'startAt',
'startedAt',
'status',
'updatedAt',
'range' => [
'max',
'min',
'type'
],
]
]
]);