接口写好了,可以用单元测试。使用注解,返回统一数据格式 这里面是用postman来操作的, 如果还是要单元测试呢? 这时候可以用到MockMvc
代码:
@RunWith(SpringRunner.class)@SpringBootTest@Slf4jpublic class TestRequestMvc { private MockMvc mockMvc; @Autowired WebApplicationContext wac; @Before public void setup() { // 初始化 this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build(); } @Test public void testGetUnit() throws Exception { mockMvc.perform(MockMvcRequestBuilders.get("/aop/getAopInfo")).andDo(print()) .andExpect(MockMvcResultMatchers.status().isOk()); } @Test public void testPostUnit() throws Exception { JSONObject json = new JSONObject(); json.put("mvcMock", "try"); mockMvc.perform(MockMvcRequestBuilders.post("/aop/postAopInfo").content(json.toJSONString()) .contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)).andDo(print()) .andExpect(MockMvcResultMatchers.status().isOk()); }}
Post请求,要设置参数和参数的格式
请求的结果:
get请求:
MockHttpServletRequest: HTTP Method = GET Request URI = /aop/getAopInfo Parameters = {} Headers = [] Body = <no character encoding set> Session Attrs = {}Handler: Type = com.yan.studyAlone.spring.aop.controller.AopController Method = public java.lang.Object com.yan.studyAlone.spring.aop.controller.AopController.configureTasks()Async: Async started = false Async result = nullResolved Exception: Type = nullModelAndView: View name = null View = null Model = nullFlashMap: Attributes = nullMockHttpServletResponse: Status = 200 Error message = null Headers = [Content-Type:"application/json;charset=UTF-8"] Content type = application/json;charset=UTF-8 Body = {"status":0,"message":null,"data":{"status":0,"message":null,"data":"I will do it","total":0},"total":0} Forwarded URL = null Redirected URL = null Cookies = []
post请求:
MockHttpServletRequest: HTTP Method = POST Request URI = /aop/postAopInfo Parameters = {} Headers = [Content-Type:"application/json;charset=UTF-8"] Body = {"mvcMock":"try"} Session Attrs = {}Handler: Type = com.yan.studyAlone.spring.aop.controller.AopController Method = public java.lang.Object com.yan.studyAlone.spring.aop.controller.AopController.getAops(com.alibaba.fastjson.JSONObject)Async: Async started = false Async result = nullResolved Exception: Type = nullModelAndView: View name = null View = null Model = nullFlashMap: Attributes = nullMockHttpServletResponse: Status = 200 Error message = null Headers = [Content-Type:"application/json;charset=UTF-8"] Content type = application/json;charset=UTF-8 Body = {"status":0,"message":null,"data":{"status":0,"message":null,"data":{"mvcMock":"try","return":"do you best!"},"total":2},"total":0} Forwarded URL = null Redirected URL = null Cookies = []
body 是目标数据
总结:
使用MockMvc可以模拟postman的请求,在测试controller里面的url是比较方便的。如果经常要调试的,不确定性比较大的(有时候思路不是很清晰或是对内容不很清楚的),还是使用postman进行比较方便,可以多次请求,确定后再使用单元测试。
今天的文章MockMvc 模拟请求分享到此就结束了,感谢您的阅读。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/11558.html