So multiple ways to do this validate the expected return using mockMVC are -
@Test
public void shouldReturnTheUserDetails() throws Exception {
var expectedJson = "{\"name\" : \"testName\", \"age\" : 10, \"gender\" : \"M\"}";
mockMvc.perform(get("/api/user")
.content("{\"name\" : \"testName\"}")
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().json(expectedJson));
}
Another way is to use the andReturn()
and then validate that -
@Test
public void shouldReturnTheUserDetails() throws Exception {
var expectedJson = "{\"name\" : \"testName\", \"age\" : 10, \"gender\" : \"M\"}";
MvcResult result = mockMvc.perform(get("/api/user")
.content("{\"name\" : \"testName\"}")
.andDo(print())
.andExpect(status().isOk())
.andReturn();
String actualJson = result.getResponse().getContentAsString();
Assert.assertEquals(expectedJson, actualJson); // or use any other library for comparison
}