4

I have constructed a list that contains Strings of a JSON object's body field names like this:

List<String> fieldNames = new ArrayList<String>();

Then I have used REST-assured to GET a response which is in JSON format like this:

{
   "id": 11,
   "name": "CoolGuy",
   "age": "80",
}

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. Here's the whole JUnit test method I've used:

@Test
public void verifyJSONMatch() {
    given()
        .auth()
        .basic("user", "pass")
        .when()
        .get(getRequestURL)
        .then()
        .body(containsString("id"));        
}
Jan Schultke
  • 17,446
  • 6
  • 47
  • 96
Clx3
  • 119
  • 1
  • 1
  • 11

3 Answers3

0

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");
dehasi
  • 2,644
  • 1
  • 19
  • 31
0

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.

0

You can

@Test
public void verifyJSONMatch() {
    given()
      .auth()
      .basic("user", "pass")
      .when()
      .get(getRequestURL)
      .then()
      .body(
        "id",is(11),
        "name", is("CoolGuy")
    ));      

}

Check this library out: https://hamcrest.org/JavaHamcrest/javadoc/1.3/org/hamcrest/Matchers.html

A.Casanova
  • 555
  • 4
  • 16