1

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 Answer 1

2

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]"));
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.