See the output from MockMvc.peform()

Lets say you have a unit test on a Spring MVC controller like this:

/**
 * Tests RESTController.getPostcode() with a false postcode and building number
 */
@Test
public void PostcodeAndBuilding_FalsePostcodeIsNotGot_Passes() throws Exception {

    mockMvc.perform(get("/postcode/" + test3PostcodeRequest + "/" + test3BuildingNumberRequest))
            .andExpect(status().isOk())
            .andExpect(content().contentType(contentType))
            .andExpect(jsonPath("$.status", is(404)));

}

The test is failing, so you want to grab the response for whatever reason.  The simply way of doing this is to return the response of the MockMvc.perform into an MvcResult and run getResponse and getContentAsString on it to turn it into a String:

/**
 * Tests RESTController.getPostcode() with a false postcode and building number
 */
@Test
public void PostcodeAndBuilding_FalsePostcodeIsNotGot_Passes() throws Exception {

    MvcResult result = mockMvc.perform(get("/postcode/" + test3PostcodeRequest + "/" + test3BuildingNumberRequest));
            //.andExpect(status().isOk())
            //.andExpect(content().contentType(contentType))
            //.andExpect(jsonPath("$.status", is(404)));

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

}

You now have the content stored as String to do with what you wish.

Facebooktwittergoogle_plusredditmail