繁体   English   中英

Spring MVC controller 测试 - 打印结果 JSON 字符串

[英]Spring MVC controller Test - print the result JSON String

嗨,我有一个 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;
}

我想看看当我运行它时 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,代码豪斯 Jackson 1.8.4

试试这段代码:

resultActions.andDo(MockMvcResultHandlers.print());

诀窍是使用andReturn()

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

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

您可以在设置MockMvc实例时启用每种测试方法的打印响应。

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

注意上面代码的.alwaysDo(MockMvcResultHandlers.print())部分。 这样就可以避免为每个测试方法应用print处理程序。

对我来说,当我使用下面的代码时,它有效:

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

它工作了!! :d

希望我可以用我的答案帮助对方

如果您正在测试Controller,则不会获得视图返回的JSon结果。 您是否可以测试视图(或测试控制器然后测试视图),或启动servlet配置器(例如Cargo),并在HTTP级别进行测试,这是检查实际情况的好方法。

对于使用 Spring Boot 的现代项目,其中MockMvc已经为您预先配置了一个@WebMvcTest “切片”测试注释,最简单的问题答案是显式添加@AutoConfigureMockMvcprintOnlyOnFailure = false

@WebMvcTest(MyController.class)
@AutoConfigureMockMvc(printOnlyOnFailure = false)
class MySlicedControllerTest {
  // ...
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM