Rest-Assured validate each item in a JSON array

8.3k Views Asked by At

Given I have this JSON array:

{
    value: ["000", "111", "345", "987"]
}

I want to use Rest-assured to validate the format of the fields using it's given/when/then structure.

given().
    queryParam("myparam", myparamvalue).
when().
    get(callRoot).
then().
    body("value", matchesPattern("[0-9][0-9][0-9]");

How do I get Rest-assured to loop through and apply the test against each value in the JSON array?

I don't know how many values will be in the JSON array. It might be only 1; it might be 100.

1

There are 1 best solutions below

0
On

You could use JsonPath and do something like the following:

given().
    queryParam("myparam", myparamvalue).
when().
    get(callRoot).
then().
  body("value.*", matchesPattern("[0-9][0-9][0-9]");

See https://github.com/rest-assured/rest-assured/wiki/usage#json-example for more details.

Or you could extract the response as a String, transform it to a JSONObject, extract the JSONArray in the values field, and then apply the regex to each item in the array:

Response response = given().queryParam("myparam", myparamvalue).when().get(callRoot).

JSONObject responseJson = new JSONObject(response.getBody().asString());
JSONArray values = responseJson.getJSONArray("values");

for(int i = 0; i < values.length(); i++) {
  String value = values.getString(i);
   Assert.assertThat(values, matchesPattern("[0-9][0-9][0-9]"));
}