引入Maven依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
测试Controller的代码
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestControllerTest {
@Autowired
private WebApplicationContext webApplicationContext;
private MockMvc mockMvc;
@Before
public void setupMockMvc(){
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
@Test
public void testTes() throws Exception{
mockMvc.perform(MockMvcRequestBuilders.get("/api/test") // 发出请求
.contentType(MediaType.APPLICATION_JSON_UTF8) //期望的内容类型
.accept(MediaType.APPLICATION_JSON_UTF8)) //期望接收的内容类型
.andExpect(MockMvcResultMatchers.status().isOk()) //期望结果是200
.andDo(MockMvcResultHandlers.print()); // 期望把结果打印出来
}
}
Mock测试打印输出的日志:
MockHttpServletRequest:
HTTP Method = GET
Request URI = /api/test
Parameters = {}
Headers = [Content-Type:"application/json;charset=UTF-8", Accept:"application/json;charset=UTF-8"]
Body = null
Session Attrs = {}
Handler:
Type = com.fubin.controller.TestController
Method = public java.lang.Object com.fubin.controller.TestController.test()
Async:
Async started = false
Async result = null
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 200
Error message = null
Headers = [Content-Type:"application/json;charset=UTF-8"]
Content type = application/json;charset=UTF-8
Body = {"id":2,"name":"fubin","age":28,"url":"https://fubin.org.cn"}
Forwarded URL = null
Redirected URL = null
Cookies = []
来源:https://www.cnblogs.com/fubinhnust/p/12013999.html