Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RestAssured: How to check the length of json array response?

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); } 
like image 950
Héctor Avatar asked Apr 07 '16 07:04

Héctor


People also ask

How do I get the size of a JSON response in Rest assured?

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.

How do I find the size of an array in JSON?

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.

How do you find the value of response body in Rest assured?

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.


2 Answers

Solved! I have solved it this way:

@Test public void test() {     RestAssured.get("/foos").then().assertThat()       .body("size()", is(2)); } 
like image 183
Héctor Avatar answered Sep 18 '22 16:09

Héctor


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)); 
like image 35
Michel Avatar answered Sep 18 '22 16:09

Michel