弹簧 MVC 控制器测试 - 打印结果 JSON 字符串

2022-08-31 13:03:44

嗨,我有一个弹簧mvc控制器

@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;
}

我想看看当我运行这个时JSON字符串会是什么样子。我写了这个测试用例

@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 ?
    }
}

如何获取 JSON 字符串?

我正在使用Spring 3,codehause Jackson 1.8.4


答案 1

试试这个代码:

resultActions.andDo(MockMvcResultHandlers.print());

答案 2

诀窍是使用andReturn()

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

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