Spring Boot微服务JUnit测试中控制台打印语句失效问题
如何在Spring Boot JUnit测试中获取并查看MockMvc的响应结果?
嘿,我看你在Spring Boot微服务的JUnit测试里碰到了控制台没打印出预期响应内容的问题,咱们来搞定它~
你现在直接打印result.getResponse(),其实得到的是MockHttpServletResponse对象的默认toString输出,它不会把响应体的具体内容展示出来,所以你看不到想要的结果。下面给你几个实用的解决办法:
直接获取响应体字符串打印
用result.getResponse().getContentAsString()就能拿到响应体的字符串内容,把这个打印出来就可以看到返回的JSON或者其他响应数据了。修改后的代码示例:@Test public void retrieveDetailsForCourse() throws Exception { Mockito.when(studentService.retrieveCourse(Mockito.anyString(), Mockito.anyString())).thenReturn(mockCourse); RequestBuilder requestBuilder = MockMvcRequestBuilders.get("/students/Student1/courses/Course1") .accept(MediaType.APPLICATION_JSON); MvcResult result = mockMvc.perform(requestBuilder).andReturn(); // 打印响应体的具体内容 System.out.println("响应体内容:" + result.getResponse().getContentAsString()); // 要是还想查看状态码、响应头这些信息,也可以这么做: System.out.println("响应状态码:" + result.getResponse().getStatus()); }用MockMvc内置的打印工具
MockMvc本身提供了更便捷的打印方式,不用手动处理MvcResult,直接在请求执行后链式调用.andDo(MockMvcResultHandlers.print()),它会自动把请求的详细信息、响应的状态码、响应体、响应头等内容都打印到控制台,信息非常全面。示例代码:@Test public void retrieveDetailsForCourse() throws Exception { Mockito.when(studentService.retrieveCourse(Mockito.anyString(), Mockito.anyString())).thenReturn(mockCourse); mockMvc.perform(MockMvcRequestBuilders.get("/students/Student1/courses/Course1") .accept(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultHandlers.print()) // 一键打印请求响应的所有详情 .andReturn(); }顺带提一下:断言响应内容
要是你不仅想查看结果,还想验证响应是否符合预期,可以用MockMvcResultMatchers来做断言,比如验证状态码是否为200,或者JSON响应里的某个字段值是否正确,这样测试会更严谨:@Test public void retrieveDetailsForCourse() throws Exception { Mockito.when(studentService.retrieveCourse(Mockito.anyString(), Mockito.anyString())).thenReturn(mockCourse); mockMvc.perform(MockMvcRequestBuilders.get("/students/Student1/courses/Course1") .accept(MediaType.APPLICATION_JSON)) .andExpect(MockMvcResultMatchers.status().isOk()) // 断言状态码为200 .andExpect(MockMvcResultMatchers.jsonPath("$.id").value("Course1")) // 断言JSON里的id字段值 .andDo(MockMvcResultHandlers.print()); // 同时打印详情方便调试 }
内容的提问来源于stack exchange,提问作者Mr.DevEng
相关产品推荐
相关产品推荐

