Laravel/PHPUnit:在未定义值的情况下断言 json 元素存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37251347/
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
Laravel/PHPUnit: Assert json element exists without defining the value
提问by Milad.Nozari
I'm sending a post request in a test case, and I want to assert that a specific element, let's say with key 'x' exists in the response. In this case, I can't say seeJson(['x' => whatever]);
because the value is unknown to me. and for sure, I can't do it with seeJson(['x']);
.
我在测试用例中发送一个 post 请求,我想断言一个特定的元素,假设响应中存在键“x”。在这种情况下,我不能说,seeJson(['x' => whatever]);
因为我不知道该值。当然,我不能用seeJson(['x']);
.
Is there a way to solve this?
有没有办法解决这个问题?
If it matters: Laravel: v5.2.31 PHPUnit: 5.3.4
如果重要:Laravel:v5.2.31 PHPUnit:5.3.4
采纳答案by Milad.Nozari
Although it's not optimal at all, I chose to use this code to test the situation:
虽然它根本不是最优的,但我选择使用这段代码来测试情况:
$this->post(URL, PARAMS)->see('x');
$this->post(URL, PARAMS)->see('x');
X is a hypothetical name, and the actual element key has a slim chance of popping up in the rest of the data. otherwise this nasty workaround wouldn't be practical.
X 是一个假设名称,实际元素键在其余数据中出现的可能性很小。否则这种讨厌的解决方法将不实用。
UPDATE:
更新:
Here's the solution to do it properly:
这是正确执行此操作的解决方案:
public function testCaseName()
{
$this->post(route('route.name'), [
'param1' => 1,
'param2' => 10,
], [
'headers_if_any' => 'value'
]);
$res_array = (array)json_decode($this->response->content());
$this->assertArrayHasKey('x', $res_array);
}
回答by Илья Савич
May it will be helpful for anyone else. You can write this test for your check response json structure
愿它对其他人有帮助。您可以为您的检查响应 json 结构编写此测试
$this->post('/api/login/', [
'email' => '[email protected]',
'password' => '123123123',
])->assertJsonStructure([
'status',
'result' => [
'id',
'email',
'full_name',
],
]);