Previosuly we have seen how to compare two Strings using JSONAssert. Now to compare an actual json response we can create a new txt file named expected.txt and put our json response in that file.
{"id":1,"firstName":"Mike","lastName":"Smith","email":"egestas.rhoncus.Proin@massaQuisqueporttitor.org","programme":"Financial Analysis","courses":["Accounting","Statistics"]}
Then we can compare our actual response that we got from server with those text file using all the 4 methods of JSONAssert and we can see whether tests pass or fail under various scenarios.
String expected = new String(Files.readAllBytes(Paths.get(System.getProperty("user.dir")+File.separator+"expected.txt")));
String actual = given().contentType(ContentType.JSON).get().asString();
1.LENIENT will only fail if firstName or any other field is different that is its in actual results and in txt file LENIENT will pass if we remove id frome expected file . i.e id will be present in actual response but will not be there in expected file.
JSONAssert.assertEquals(expected, actual,JSONCompareMode.LENIENT);
2.STRICT will fail if we remove id from expected file . i.e id will be present in actual response but will not be there in expected file.STRICT will also fail if we change ordering on an array. i.e in courses we put statistics in front of accounting in our txt file.
JSONAssert.assertEquals(expected, actual,JSONCompareMode.STRICT);
3.STRICT_ORDER will pass if we remove id from expected file . i.e id will be present in actual response but will not be there in expected file as STRICT_ORDERING has nothing to do with extensibility. But it will fail if we change ordering on an array. i.e in courses we put statistics in front of accounting in our txt file.
JSONAssert.assertEquals(expected, actual,JSONCompareMode.STRICT_ORDER);
4.NON_EXTENSIBLE will FAIL if we remove id from expected file . i.e id will be present in actual response but will not be there in expected file as it is all about extensibility. But NON_EXTENSIBLE will pass if we change ordering on an array. i.e in courses we put statistics in front of accounting in our txt file.
JSONAssert.assertEquals(expected, actual,JSONCompareMode.NON_EXTENSIBLE);
To know more about the 4 methods we used above please visit the below link.
http://jsonassert.skyscreamer.org/javadoc/org/skyscreamer/jsonassert/JSONCompareMode.html