@SpringBootTest 中加入参数webEnvironment 并根据需求设置值
.RANDOM_PORT随机端口号
.DEFINED_PORT默认端口号
.none 不启动web环境
例:
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
表示开启web虚拟环境,测试的端口号随机
@AutoConfigureMockMvc 开启虚拟mvc调用
@Autowired MockMvc mockMvc 注入虚拟mvc调用对象
mockMvc.perform() 执行请求
MockMvcRequestBuilders.请求方式(“路径”) 创建虚拟请求
例:
@Test
public void test(@Autowired MockMvc mockMvc) throws Exception {
// 创建虚拟请求,访问/books。get方式请求
RequestBuilder builder = MockMvcRequestBuilders.get("/books");
// 执行请求
ResultActions perform = mockMvc.perform(builder);
}
匹配执行状态MockMvcResultMatchers
他有很多种匹配方式比如:
.status()匹配执行状态
.header()匹配响应头
.content()匹配响应体 等等
.status()匹配执行状态StatusResultMatchers
定义本次调用的执行状态预期值
StatusResultMatchers status = MockMvcResultMatchers.status();
Status有很多种预期值
例如
ResultMatcher ok = status.isOk();预计本次调用是成功的
ResultMatcher notFound = status.isNotFound();预计本次调用找不到路径
.header()匹配响应头HeaderResultMatchers
定义本次调用的响应头期值
HeaderResultMatchers header = MockMvcResultMatchers.header();
把期望的key和value放到对应位置
ResultMatcher string = header.string("key","value");
.content()匹配响应体ContentResultMatchers
定义本次调用的响应体期值(json)
ContentResultMatchers content = MockMvcResultMatchers.content();
ResultMatcher books = content.json(“字符串”)
定义本次调用的响应体期值(字符串)
ContentResultMatchers content = MockMvcResultMatchers.content();
ResultMatcher books = content.string(“字符串”)
例:
// 在test中进行web测试
@Test
public void testall(@Autowired MockMvc mockMvc) throws Exception {
// 发起虚拟请求
RequestBuilder builder = MockMvcRequestBuilders.get("/books");
ResultActions perform = mockMvc.perform(builder);
// 测试是否响应成功
StatusResultMatchers status = MockMvcResultMatchers.status();
ResultMatcher ok = status.isOk();
perform.andExpect(ok);
// 测试响应头Content-Type的值是否为application/json
HeaderResultMatchers header = MockMvcResultMatchers.header();
ResultMatcher string = header.string("Content-Type", "application/json");
perform.andExpect(string);
// 测试响应体的数据是否为{"data":[],"code":20041,"msg":"查询成功"}
ContentResultMatchers content = MockMvcResultMatchers.content();
ResultMatcher books = content.json("{\"data\":[{\"booksname\":\"三国演义\",\"author\":\"罗贯中\",\"num\":154,\"price\":135,\"id\":1}],\"code\":20041,\"msg\":\"查询成功\"}");
perform.andExpect(books);
}