在 PhpUnit 测试中匹配 JsonStructure - Laravel 5.4
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42657551/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Match JsonStructure in PhpUnit Test - Laravel 5.4
提问by Farooq Ahmed Khan
I am creating a unit test and want to test the JSON
structure returned in the response. I am aware that the TestResponse
provides a method assertJsonStructure
to match the structure of your JSON
response. But for some reason I am unable to map the $structure
to my response and in result the test fails. Let me share the required snippets.
我正在创建一个单元测试并想测试JSON
响应中返回的结构。我知道TestResponse
提供了一种方法assertJsonStructure
来匹配您的JSON
响应结构。但由于某种原因,我无法将 映射$structure
到我的响应,结果测试失败。让我分享所需的片段。
Endpoint Response
端点响应
{
"status": true,
"message": "",
"data": [
{
"id": 2,
"name": "Shanelle Goodwin",
"email": "[email protected]",
"created_at": "2017-03-05 16:12:49",
"updated_at": "2017-03-05 16:12:49",
"user_id": 1
}
]
}
Test Function
测试功能
public function testEndpoint(){
$response = $this->get('/api/manufacturer/read', [], $this->headers);
$response->assertStatus(200);
$response->assertJsonStructure([
'status',
'message',
'data' => [
{
'id',
'name',
'email',
'created_at',
'updated_at',
'user_id'
}
]
]);
var_dump("'/api/manufacturer/read' => Test Endpoint");
}
There can multiple nodes in data
array so that is why i tried to mention the array in structure but seems it doesn't map correctly.Any help would be appreciated :-)
data
数组中可以有多个节点,这就是为什么我试图在结构中提及数组,但似乎它没有正确映射。任何帮助将不胜感激:-)
回答by Farooq Ahmed Khan
Luckily, playing with different options I have solved this issue. A '*' is expected as key if we are to match a nested object in an array. We can see the reference here.
幸运的是,使用不同的选项我已经解决了这个问题。如果我们要匹配数组中的嵌套对象,则应将“*”作为键。我们可以在这里看到参考。
I have set the structure like this for array of
objects`
我已经这样设置结构array of
objects`
$response->assertJsonStructure([
'status',
'message',
'data' => [
'*' => [
'id',
'name',
'email',
'created_at',
'updated_at',
'user_id'
]
]
]);
And if you want to match just a single object
如果您只想匹配单个对象
$response->assertJsonStructure([
'status',
'message',
'data' => [
[
'id',
'name',
'email',
'created_at',
'updated_at',
'user_id'
]
]
]);
回答by Marcin Nabia?ek
I think you should use:
我认为你应该使用:
$response->assertJsonStructure([
'status',
'message',
'data' => [
[ // change here
'id',
'name',
'email',
'created_at',
'updated_at',
'user_id'
] // change here
]
]);