Spring MVC controller Test - print the result JSON String

前端 未结 5 2099
一向
一向 2021-01-30 05:03

Hi I have a Spring mvc controller

@RequestMapping(value = \"/jobsdetails/{userId}\", method = RequestMethod.GET)
@ResponseBody
public List jobsDetai         


        
相关标签:
5条回答
  • 2021-01-30 05:28

    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.

    0 讨论(0)
  • 2021-01-30 05:32

    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.

    0 讨论(0)
  • 2021-01-30 05:36

    Try this code:

    resultActions.andDo(MockMvcResultHandlers.print());
    
    0 讨论(0)
  • 2021-01-30 05:40

    The trick is to use andReturn()

    MvcResult result = springMvc.perform(MockMvcRequestBuilders
             .get("/jobsdetails/2").accept(MediaType.APPLICATION_JSON)).andReturn();
    
    String content = result.getResponse().getContentAsString();
    
    0 讨论(0)
  • 2021-01-30 05:50

    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

    0 讨论(0)
提交回复
热议问题