Java Spring MVC 控制器测试 - 打印结果 JSON 字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21495296/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 09:00:53  来源:igfitidea点击:

Spring MVC controller Test - print the result JSON String

javajsonspring-mvcjunit4

提问by iCode

Hi I have a Spring mvc controller

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

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

我想看看运行它时 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 ?
    }
}

How to get the JSON string?

如何获取JSON字符串?

I am using Spring 3, codehause Hymanson 1.8.4

我正在使用 Spring 3,codehause Hymanson 1.8.4

采纳答案by JB Nizet

Try this code:

试试这个代码:

resultActions.andDo(MockMvcResultHandlers.print());

回答by jax

The trick is to use andReturn()

诀窍是使用 andReturn()

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

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

回答by funkygono

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.

如果您正在测试控制器,您将不会获得视图返回的 JSon 结果。您是否可以测试视图(或测试控制器然后测试视图),或者启动一个 servlet 约束器(例如使用 Cargo),并在 HTTP 级别进行测试,这是检查真正发生了什么的好方法。

回答by Chris Sim

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

它奏效了!!:D

Hope I can help the other with my answer

希望我的回答能帮助到对方

回答by uiroshan

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

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

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.

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