'Rest assured verify that a JSON body contains all Strings from a List
So basically, i have constructed a list that contains Strings of a JSON object's body field names.
Something like this:
List<String> fieldNames = new ArrayList<String>();
Then I have used Rest-assured to GET a response which is in JSON format something like this:
{
"id": 11,
"name": "CoolGuy",
"age": "80",
}
So my list contains "id", "name" and "age". How can i verify that JSON fields match those strings in my list. WITHOUT depending on their order.
I only know how to verify that it contains one String and here's the whole JUnit test method I used:
@Test
public void verifyJSONMatch() {
given().auth().basic("user", "pass").when()
.get(getRequestURL).then().body(containsString("id"));
}
Any suggestions?
Solution 1:[1]
You can extract the response
ResponseOptions response = given().spec(request)
.get("/url_path");
And then parse a json
DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
assertThatJson(parsedJson).field("['id']").isEqualTo("11");
Solution 2:[2]
It would probably be easiest to extract the response as a Java Object and then just assert that the extracted object is equal to the one you have above in JSON.
MyObject expectedObject = new MyObject(11, "CoolGuy", "80");
MyObject myObject =
given().auth().basic("user", "pass")
.when().get(getRequestURL)
.then().extract().response().as(MyObject.class);
assertEquals(expectedObject, myObject);
You could make the constructor for that whatever you want. I assume your object may be much more complicated than what is shown above. However, this is a much easier way to assert equality, and it is easily reusable.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Zach Johnson |
