Spring MVC controller Test - print the result JSON String
Asked Answered
O

6

83

Hi I have a Spring mvc controller

@RequestMapping(value = "/jobsdetails/{userId}", method = RequestMethod.GET)
@ResponseBody
public List<Jobs> jobsDetails(@PathVariable Integer userId,HttpServletResponse response) throws IOException {
    try {       
        Map<String, Object> queryParams=new LinkedHashMap<String, Object>(); 

        queryParams.put("userId", userId);

        jobs=jobsService.findByNamedQuery("findJobsByUserId", queryParams);

    } catch(Exception e) {
        logger.debug(e.getMessage());
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
    }
    return jobs;
}

I want to see how the JSON String will looks like when I run this. I wrote this test case

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration("classpath:webapptest")
@ContextConfiguration(locations = {"classpath:test-applicationcontext.xml"})
public class FindJobsControllerTest {
private MockMvc springMvc;

    @Autowired
    WebApplicationContext wContext;

    @Before
    public void init() throws Exception {
        springMvc = MockMvcBuilders.webAppContextSetup(wContext).build();
    }

    @Test
    public void documentsPollingTest() throws Exception {
        ResultActions resultActions = springMvc.perform(MockMvcRequestBuilders.get("/jobsdetails/2").accept(MediaType.APPLICATION_JSON));

        System.out.println(/* Print the JSON String */); //How ?
    }
}

How to get the JSON string?

I am using Spring 3, codehause Jackson 1.8.4

Oke answered 1/2, 2014 at 7:14 Comment(0)
A
205

Try this code:

resultActions.andDo(MockMvcResultHandlers.print());
Archive answered 1/2, 2014 at 8:29 Comment(1)
Thank you for not just using print() but adding its class name, unlike many other search results!Overspread
T
74

The trick is to use andReturn()

MvcResult result = springMvc.perform(MockMvcRequestBuilders
         .get("/jobsdetails/2").accept(MediaType.APPLICATION_JSON)).andReturn();

String content = result.getResponse().getContentAsString();
Theologize answered 1/2, 2014 at 8:43 Comment(0)
C
24

You can enable printing response of each test method when setting up the MockMvc instance.

springMvc = MockMvcBuilders.webAppContextSetup(wContext)
               .alwaysDo(MockMvcResultHandlers.print())
               .build();

Notice the .alwaysDo(MockMvcResultHandlers.print()) part of the above code. This way you can avoid applying print handler for each test method.

Chace answered 20/6, 2017 at 6:7 Comment(0)
H
10

For me it worked when I used the code below:

ResultActions result =
     this.mockMvc.perform(post(resource).sessionAttr(Constants.SESSION_USER, user).param("parameter", "parameterValue"))
        .andExpect(status().isOk());
String content = result.andReturn().getResponse().getContentAsString();

And it worked !! :D

Hope I can help the other with my answer

Hirsute answered 5/8, 2016 at 11:51 Comment(0)
D
0

If you are testing the Controller, you won't get the JSon result, which is returned by the view. Whether you can test the view (or test the controller and then the view), or starting a servlet contrainer (with Cargo for example), and test at HTTP level, which is a good way to check what really happen.

Doublespace answered 1/2, 2014 at 9:27 Comment(2)
Actually you can get the JSON response from the controller using .andReturn()Theologize
Oh yes, that's true, I just saw this in your answer. I didn't know Spring offered so much mocks, that's very great.Doublespace
S
0

For modern projects using Spring Boot, where MockMvc is already pre-configured for you with a single @WebMvcTest "slicing" test annotation, the easiest answer to the question would be explicitly adding @AutoConfigureMockMvc with printOnlyOnFailure = false:

@WebMvcTest(MyController.class)
@AutoConfigureMockMvc(printOnlyOnFailure = false)
class MySlicedControllerTest {
  // ...
}
Skiplane answered 28/8, 2022 at 11:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.