javarest-assuredhamcrestrest-assured-jsonpath

Using REST assured with Java Hamcrest to check if Array contains item with multiple key value pairs where the values have a different type


An api returns an array with json objects. I want to check if an object in the array exists which has certain key value entries. The approach im using does not work when the value type is different.

"$", hasItem(
    allOf(
        hasEntry("id", "someid123"),
        hasEntry("age", 99)
    )
 );

My IDE gives the error:

Cannot resolve method 'allOf(Matcher<Map<? extends K, ? extends V>>, Matcher<Map<? extends K, ? extends V>>)'

This method would work if 99 were a String, but in this case I can not control that the API returns a number.

Does anyone know a way to get this done?

Example response body Im trying to parse:

[ 
  {
    "id": "someid123",
    age: 99
  },
  {
    "id": "anotherid789",
    age: 77
  }
]

The objects get converted into java maps internally I think.


Solution

  • This is the specific of Java generics which can (and they actually do) align the argument types for the methods.

    You can work that around with the help of JsonPath like I'm showing below:

    public static void main(String[] args) {
        RestAssured.baseURI = "http://demo1954881.mockable.io";
        Response resp =
                given().
                        when().get("/collectionTest")
                        .then().extract().response();
        resp.then()
            .body("findAll{i -> i.id == 'someid123' && i.age == 99}", not(empty()));
    }
    

    So basically you're filtering the collection with the help of JsonPath and then assert that it is not empty.