【问题标题】:Rest Assured - compare json response with local json file放心 - 将 json 响应与本地 json 文件进行比较
【发布时间】:2020-06-20 00:08:56
【问题描述】:

我有一个本地 json 文件 test.json

[
  {
    "id": 1,
    "title": "test1"
  },
  {
    "id": 2,
    "title": "test2"
  }
]

读取json文件的类

public static String getFileContent(String fileName){
        String fileContent = "";
        String filePath = "filePath";
        try {
            fileContent = new String(Files.readAllBytes(Paths.get(filePath)));
            return fileContent;
        }catch(Exception ex){
            ex.printStackTrace();
        }finally{
            return fileContent;
        }
    }

我使用放心发出请求并得到相同的 json 响应

String fileContent= FileUtils.getFileContent("test.json");

    when().
       get("/testurl").
    then().
       body("", equalTo(fileContent));

这是我从本地文件中得到的

[\r\n  {\r\n    \"id\": 1,\r\n    \"title\": \"test1\"\r\n  },\r\n  {\r\n    \"id\": 2,\r\n    \"title\": \"test2\"\r\n  }\r\n]

这是实际的响应:

[{id=1, title=test1}, {id=2, title=test2}]

有没有更好的方法来比较这两者?我尝试做类似fileContent.replaceAll("\\r\\n| |\"", ""); 的事情,但它只是删除了所有空间[{id:1,title:test1},{id:2,title:test2}] 有什么帮助吗?或者任何只比较内容而忽略换行符、空格和双引号的方法?

【问题讨论】:

  • 这能回答你的问题吗? Full Json match with RestAssured
  • 参考使用 Hamcrest Matchers 的@Hac 给出的答案。
  • @kaweesha - 我在发布答案之前检查了该帖子,expectedJson.getMap("") 在 JSON 作为 ArrayList 时不起作用,这里的工作解决方案是 expectedJson.getList("")

标签: json string-comparison rest-assured


【解决方案1】:

您可以使用以下任何一种方法

JsonPath:

String fileContent = FileUtils.getFileContent("test.json");

    JsonPath expectedJson = new JsonPath(fileContent);
    given().when().get("/testurl").then().body("", equalTo(expectedJson.getList("")));

杰克逊:

String fileContent = FileUtils.getFileContent("test.json");
String def = given().when().get("/testurl").then().extract().asString();

    ObjectMapper mapper = new ObjectMapper();
    JsonNode expected = mapper.readTree(fileContent);
    JsonNode actual = mapper.readTree(def);
    Assert.assertEquals(actual,expected);

GSON:

String fileContent = FileUtils.getFileContent("test.json");
String def = given().when().get("/testurl").then().extract().asString();

    JsonParser parser = new JsonParser();
    JsonElement expected = parser.parse(fileContent);
    JsonElement actual = parser.parse(def);
    Assert.assertEquals(actual,expected);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-18
    • 2012-10-25
    • 2018-06-18
    • 1970-01-01
    • 2019-01-24
    • 1970-01-01
    相关资源
    最近更新 更多