【问题标题】:Spring MVC controller Test - print the result JSON StringSpring MVC 控制器测试 - 打印结果 JSON 字符串
【发布时间】:2014-02-25 01:06:57
【问题描述】:

您好,我有一个 Spring 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

【问题讨论】:

    标签: java json spring-mvc junit4


    【解决方案1】:

    试试这个代码:

    resultActions.andDo(MockMvcResultHandlers.print());
    

    【讨论】:

    • 感谢您不仅使用print(),还添加了它的类名,这与许多其他搜索结果不同!
    【解决方案2】:

    诀窍是使用andReturn()

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

      • 其实你可以使用 .andReturn() 从控制器获取 JSON 响应
      • 哦,是的,这是真的,我刚刚在您的回答中看到了这一点。我不知道 Spring 提供了这么多模拟,这非常棒。
      【解决方案4】:

      对我来说,当我使用下面的代码时它起作用了:

      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

      希望我的回答可以帮助对方

      【讨论】:

        【解决方案5】:

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

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

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-02-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-07-19
          • 1970-01-01
          • 2013-08-11
          相关资源
          最近更新 更多