0

I have a local json file test.json

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

Class to read the json file

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;
        }
    }

I use rest assured to make the request and get same json response back

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

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

This is what I got from local file

[\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]

This is the actual response:

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

Is there any better way to compare those two? I try to do something like fileContent.replaceAll("\\r\\n| |\"", ""); but it just removed all the space [{id:1,title:test1},{id:2,title:test2}] Any help? Or any ways that just compare the content and ignore newline, space and double quote?

HenlenLee
  • 435
  • 1
  • 11
  • 30
  • Does this answer your question? [Full Json match with RestAssured](https://stackoverflow.com/questions/44716665/full-json-match-with-restassured) – kaweesha Jun 20 '20 at 04:47
  • Refer the answer given by @Hac which uses Hamcrest Matchers. – kaweesha Jun 20 '20 at 04:48
  • @kaweesha - I checked that post before posting my answer, `expectedJson.getMap("")` doesn't work when the JSON is as an ArrayList, The working solution here is `expectedJson.getList("")` – Wilfred Clement Jun 20 '20 at 07:41

1 Answers1

2

You can use any of the following methods

JsonPath :

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

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

Jackson :

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);
Wilfred Clement
  • 2,674
  • 2
  • 14
  • 29