我用 Laravel 准备了一个示例 API。它总是返回这个对象:
{
"a": 1,
"b": 2
}
现在,我想更好地了解如何使用 phpunit
进行测试。我发现有 assertJson
和 assertJsonFragment
方法,但我无法理解它们之间的区别。
假设我想断言响应的确切结构,因此它需要是 a=1
和 b=2
,仅此而已。起初,我确信这会起作用:
$response = $this->get('/api/foo');
$response->assertStatus(200)
->assertJson(['a' => 1, 'b' => 2]);
它将通过测试,但问题是,如果我向响应添加更多属性(例如 c=3
或其他属性),它仍然会通过测试。然后是 assertJsonFragment
方法,对于我的测试,该方法的行为相同,只是给出不同的错误消息。
assertJson 是否有错误?有没有其他方法可以完成我想做的事情,即确保响应是这组特定的属性?
在 Laravel 5.6 和 5.7 上测试。
最佳答案
来自here :
The
assertJson
method converts the response to an array and utilizesPHPUnit::assertArraySubset
to verify that the given array exists within the JSON response returned by the application. So, if there are other properties in the JSON response, this test will still pass as long as the given fragment is present.
更重要的是,实现你想要的:
If you would like to verify that the given array is an exact match for the JSON returned by the application, you should use the
assertExactJson
method
关于php - 使用 Laravel 测试 JSON 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52335182/