- 前言
- 匹配执行状态
- 匹配body
- 匹配json
- 匹配header
测试用例匹配响应结果
匹配执行状态状态匹配
@SpringBootTest(webEnvironment =SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc //开启mvc调用
public class WebTest {
//通过形参方式注入Mvc对象
@Test
void hello2(@Autowired MockMvc mockMvc) throws Exception {
//创建请求,http://localhost:xxxx/hello
MockHttpServletRequestBuilder builder= MockMvcRequestBuilders.get("/hello2");
ResultActions action=mockMvc.perform(builder);
StatusResultMatchers status= MockMvcResultMatchers.status(); //定义预期执行状态
ResultMatcher ok=status.isOk();//设定的预期状态
//将请求结果与预期结果比对
action.andExpect(ok);
}
}
执行结果
(更改了请求链接)失败的结果
MockHttpServletRequest:
HTTP Method = GET
Request URI = /hello2
Parameters = {}
Headers = []
Body = null
Session Attrs = {}
Handler:
Type = org.springframework.web.servlet.resource.ResourceHttpRequestHandler
Async:
Async started = false
Async result = null
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 404
Error message = null
Headers = [Vary:"Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers"]
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
java.lang.AssertionError: Status expected:<200> but was:<404>
Expected :200
Actual :404
匹配body
//通过形参方式注入Mvc对象
@Test
void hello3(@Autowired MockMvc mockMvc) throws Exception {
//创建请求,http://localhost:xxxx/hello
MockHttpServletRequestBuilder builder= MockMvcRequestBuilders.get("/hello");
ResultActions action=mockMvc.perform(builder);
ContentResultMatchers content= MockMvcResultMatchers.content();
ResultMatcher ok=content.string("hello");
//将请求结果与预期结果比对
action.andExpect(ok);
}
匹配返回结果与预期是否一致
//创建请求,http://localhost:xxxx/hello
MockHttpServletRequestBuilder builder= MockMvcRequestBuilders.get("/getById");
ResultActions action=mockMvc.perform(builder);
ContentResultMatchers content= MockMvcResultMatchers.content();
ResultMatcher result=content.json("{"id":1,"name":"wangsan"}");
//将请求结果与预期结果比对
action.andExpect(result);
结果
略
//创建请求,http://localhost:xxxx/hello
MockHttpServletRequestBuilder builder= MockMvcRequestBuilders.get("/getById");
ResultActions action=mockMvc.perform(builder);
HeaderResultMatchers header= MockMvcResultMatchers.header();
ResultMatcher result=header.string("Content-Type","application/json");//匹配响应头
//将请求结果与预期结果比对
action.andExpect(result);
结果
略



