接口写好了,可以用单元测试。使用注解,返回统一数据格式 这里面是用postman来操作的, 如果还是要单元测试呢? 这时候可以用到MockMvc
代码:
@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
public 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 = null
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
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 = null
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
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进行比较方便,可以多次请求,确定后再使用单元测试。