RestAssured: How to check json array response length?

I have an endpoint that returns JSON as:

[ {"id" : 4, "name" : "Name4"}, {"id" : 5, "name" : "Name5"} ] 

and class DTO:

 public class FooDto { public int id; public String name; } 

Now I am testing the length of the returned json array as follows:

 @Test public void test() { FooDto[] foos = RestAssured.get("/foos").as(FooDto[].class); assertThat(foos.length, is(2)); } 

But is there a way to do this without adding FooDto to the array? Something like that:

 @Test public void test() { RestAssured.get("/foos").then().assertThat() .length(2); } 
+13
source share
5 answers

Solved! I solved it like this:

 @Test public void test() { RestAssured.get("/foos").then().assertThat() .body("size()", is(2)); } 
+37
source

There are ways. I decided using below

 @Test public void test() { ValidatableResponse response = given().when().get("/foos").then(); response.statusCode(200); assertThat(response.extract().jsonPath().getList("$").size(), equalTo(2)); } 

using restassured 3.0.0

+4
source

I solved a similar problem with GPath.

 Response response = requestSpec .when() .get("/new_lesson") .then() .spec(responseSpec).extract().response(); 

Now I can extract the response body as a String and use the GPath built-in features

 String responseBodyString = response.getBody().asString(); assertThat(from(responseBodyString).getList("$").size()).isEqualTo(YOUR_EXPECTED_SIZE_VALUE); assertThat(from(responseBodyString).getList("findAll { it.name == 'Name4' }").size()).isEqualTo(YOUR_EXPECTED_SUB_SIZE_VALUE); 

For a complete example, see http://olyv-qa.blogspot.com/2017/07/restassured-short-example.html

+4
source

@ Hector

 [ {"id" : 4, "name" : "Name4"}, {"id" : 5, "name" : "Name5"} ] 

This was a really bad example. Here you have the matrix [2,2].

If you create something like this:

 [ {"id" : 4, "name" : "Name4"}, {"id" : 5, "name" : "Name5"}, {"id" : 6, "name" : "Name6"} ] 

Now you will still pass the test:

 @Test public void test() { RestAssured.get("/foos").then().assertThat() .body("size()", is(2)); } 

Think about whether it was intentional. body("size()",is(2)); represents body("size()",is(2)); Have a check on the length of one node instead of the number of records in the response.

+2
source

This is what you need to do to get the size.

 Response response = given() .header("Accept","application/json") .when() .get("/api/nameofresource") .then() .extract() .response(); 

After receiving the answer, you can do the following to get the size.

int size = response.jsonPath (). getList ("id"). size ();

I hope this helps. :)

0
source

All Articles