php - 使用 Laravel 测试 JSON 响应

标签 php json laravel phpunit

我用 Laravel 准备了一个示例 API。它总是返回这个对象:

{
    "a": 1,
    "b": 2
}

现在,我想更好地了解如何使用 phpunit 进行测试。我发现有 assertJsonassertJsonFragment 方法,但我无法理解它们之间的区别。

假设我想断言响应的确切结构,因此它需要是 a=1b=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 utilizes PHPUnit::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/

相关文章:

php - PDOStatement::bindParam,使用 PDO::PARAM_STR 长度指定了什么?

Laravel迁移使多个主键失败

php - 使用 PHP 向 mysql 添加空行的准备语句

php - 这是在 zend 框架中制作表单的最佳方式

javascript - 使用jquery自动完成我试图获取文本框中的值作为表数据不是来自在文本字段中使用ajax的json

json - 如何在 vscode 中获取 Protractor 或 json 智能感知

javascript - 显示数据库中的数据而不重新加载

php - Laravel:获取所有值并根据 bool 属性进行检查

php - 用 Guzzle 执行 "curl -u"

javascript - 将 Knockout JS 对象与 Javascript 对象合并