Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get size of json from MvcResult

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.

like image 703
annswerg Avatar asked Jul 11 '26 04:07

annswerg


2 Answers

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))
like image 176
Nicola Ambrosetti Avatar answered Jul 13 '26 17:07

Nicola Ambrosetti


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))
like image 40
Rodrigo Villalba Zayas Avatar answered Jul 13 '26 18:07

Rodrigo Villalba Zayas