Search code examples
javarest-assuredmatcherhamcrestrest-assured-jsonpath

Multiple matches assertion in JSON via RestAssured


I have several JSON objects in response which contain certain id in each one of them.

{
"data": [{
        "id": 1,
        "status": {
            "id": 0
        }
    },
    {
        "id": 2,
        "status": {
            "id": 0
        }
    },
    {
        "id": 3,
        "status": {
            "id": 0
        }

    }
]

}

I need to test that every data.status.id has certain value:

    then().
        spec(basicResponse).
        body("data.status.id", equalTo(0));

But equalTo matcher comperes expected value with the whole list of the found ids at once. Not with each individual found id separately.

java.lang.AssertionError: 1 expectation failed.
JSON path data.status.id doesn't match.
Expected: 0
  Actual: [0, 0, 0]

How can I test it without extracting response data to List and then check it through foreach or something like that?

int statusNeeded = 0;
            List<int> idsList = given().
                     get(Endpoints.GetCampaigns).
                 then().
                     extract().body().jsonPath().getList("data.status.id");

    for (int statusId: idsList)
    if(!statusNeeded.equals(statusId)) Assert.fail("Some id is not " + statusNeeded);

Solution

  • Unfortunately, you do not describe further the structure of your JSON output. So, I'm forced to guess. Why don't you try?

    $.data[0].status.id