I have an endpoint that returns a JSON like:
[ {"id" : 4, "name" : "Name4"}, {"id" : 5, "name" : "Name5"} ]
and a DTO class:
public class FooDto { public int id; public String name; }
Now, I'm testing the length of the returned json array this way:
@Test public void test() { FooDto[] foos = RestAssured.get("/foos").as(FooDto[].class); assertThat(foos.length, is(2)); }
But, is there any way to do it without cast to FooDto array? Something like this:
@Test public void test() { RestAssured.get("/foos").then().assertThat() .length(2); }
We can get the size of an array within a nested JSON in Rest Assured. First, we shall obtain a Response body which is in JSON format from a request. Then convert it to string. Finally, to obtain JSON array size, we have to use the size method.
To obtain the size of a JSON-encoded array or object, use the json_size function, and specify the column containing the JSON string and the JSONPath expression to the array or object.
Get a value from the response body using the JsonPath or XmlPath syntax. REST Assured will automatically determine whether to use JsonPath or XmlPath based on the content-type of the response. If no content-type is defined then REST Assured will try to look at the "default parser" if defined (RestAssured.
Solved! I have solved it this way:
@Test public void test() { RestAssured.get("/foos").then().assertThat() .body("size()", is(2)); }
You can simply call size()
in your body path:
Like:
given() .accept(ContentType.JSON) .contentType(ContentType.JSON) .auth().principal(createPrincipal()) .when() .get("/api/foo") .then() .statusCode(OK.value()) .body("bar.size()", is(10)) .body("dar.size()", is(10));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With