Springboot的MockMvc调⽤api层接⼝
如何测试Controller对外提供的接⼝
- 增加类注解 @AutoConfigureMockMvc
- 注⼊⼀个MockMvc类
- 相关API :
- perform执⾏⼀个RequestBuilder请求
- andExpect:添加ResultMatcher->MockMvcResultMatchers验证规则
- andReturn:最后返回相应的MvcResult->Response
@AutoConfigureMockMvc
public class VideoTest {
@Autowired
private MockMvc mockMvc;
@Test
public void testVideoListApi() throws Exception{
MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/pub/video/list"))
.andExpect(MockMvcResultMatchers.status().isOk()).andReturn();
int status =mvcResult.getResponse().getStatus();
System.out.println(status);
String result=mvcResult.getResponse().getContentAsString(Charset.forName("utf-8"));
System.out.println(result);
}