Springboot的MockMvc调用api层接口进行单元测试

如何测试Controller对外提供的接⼝

1.增加类注解 @AutoConfigureMockMvc
2.注⼊⼀个MockMvc类

相关API : perform执⾏⼀个RequestBuilder请求
andExpect:添加ResultMatcher->MockMvcResultMatchers验证规则
andReturn:最后返回相应的MvcResult->Response

code:

其中DemoProjectApplication是我的启动类
在这里插入图片描述
get或post等等
后面是接口 根据自己需求来


@RunWith(SpringRunner.class)  //底层用junit  SpringJUnit4ClassRunner
@SpringBootTest(classes={DemoProjectApplication.class})//启动整个springboot工程
@AutoConfigureMockMvc
@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();
 // 使⽤下⾯这个,增加 编码 说明,就不会乱码打印
 String result =
mvcResult.getResponse().getContentAsString(Charset.forName("utf-8"));
 System.out.println(result);
 }

运行结果:

绿色箭头代表测试成功
在这里插入图片描述


版权声明:本文为weixin_45678130原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。