How to check JSON in response body with mockMvc
Solution 1:
I use TestNG for my unit testing. But in Spring Test Framework they both looks similar. So I believe your test be like below
@Test
public void testAlertFilterView() throws Exception {
this.mockMvc.perform(get("/getServerAlertFilters/v2v2v2/").
.andExpect(status().isOk())
.andExpect(content().json("{'data':[{'useRegEx':'false','hosts':'v2v2v2'}]}"));
}
If you want check check json Key and value you can use jsonpath
.andExpect(jsonPath("$.yourKeyValue", is("WhatYouExpect")));
You might find thatcontent().json()
are not solveble please add
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
Solution 2:
The 406 Not Acceptable
status code means that Spring couldn't convert the object to json. You can either make your controller method return a String and do return json.toString();
or configure your own HandlerMethodReturnValueHandler
. Check this similar question Returning JsonObject using @ResponseBody in SpringMVC