2

I'm testing an API and get all data from the DB. I save the response as

MvcResult result = mockMvc.perform(..some code..).andReturn();

I get a json as response. I want to get the length of json array. So, if I have 2 rows in DB, I want to get 2 as a result.

Or is there maybe another way to count number of rows which are present in the DB.

Nicola Ambrosetti
  • 2,539
  • 3
  • 23
  • 34
annswerg
  • 239
  • 5
  • 16
  • Usually response of multiple rows will be an array, like `[ {row1},{row2},.., ]`. So you can `simply use array.length` property. – Narendhran Aug 06 '19 at 11:12
  • @Narendhran, I have an array, but I don't see in MvcResult methods to convert in to array or to get length array length... – annswerg Aug 06 '19 at 11:16
  • there are lot of third party library out there to convert json string to object, some of the famous libraries are Jackson, GSON – Narendhran Aug 06 '19 at 11:20

5 Answers5

4

Since you are using MockMvc instead of returning with andReturn() you can use the JSONPath support like:

  mvc.perform( MockMvcRequestBuilders
  .get("/resource")
  .accept(MediaType.APPLICATION_JSON))
  .andExpect(status().isOk())
  .andExpect(MockMvcResultMatchers.jsonPath("$.length").value(2))
Nicola Ambrosetti
  • 2,539
  • 3
  • 23
  • 34
2

if you want to get json array length this is the way,

1.if you import org.json.simple.JSONArray you can use JSONArray.size()

2.if you import org.json.JSONArray you can use JSONArray.length()

2

Let's say your response is something like this:

{
  result : [
     {
       "field1": "a",
       "field2": "b"
     },
     {
       "field1": "c",
       "field2": "d"
     }
  ]
}

In this case you'd use MockMvc to write assertions like this:

mvc.perform(MockMvcRequestBuilders
.get("/resource")
.accept(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.result.length()").value(2))
Rodrigo Villalba Zayas
  • 4,836
  • 2
  • 21
  • 36
0

Try:

String content = result.getResponse().getContentAsString();

and then try this one

user3506652
  • 43
  • 1
  • 2
  • 8
0

Use com.jayway.JsonPath (you already have this class through spring-boot-starter-test )

Integer length = JsonPath.read(result.getResponse().getContentAsString(), "$.length()");
beatrice
  • 2,768
  • 3
  • 17
  • 31