MockMvc 是springTest提供的对SpringMvc提供的测试工具。这样可以让单元测试不仅仅局限于对Dao和Service 层的测试。同时,也可以测试Controller层。丰富的单元测试的功能。测试时不用频繁重启servlet容器,简化了测试操作。
MockMvc需要ServletContext来模拟用户的请求和相应。
首选,需要在测试类头部添加一下Annotation
@WebAppConfiguration
@RunWith(SpringJUnit4Cla***unner.class)
@ContextConfiguration(locations = { "classpath:spring/applicationContext.xml" })
接下来就可以在junit中编写测试类了。
demo 1 有请求头、无参数的get请求
样例代码如下:
@Test
public void 测试类() throws Exception {
ResultActions reaction=this.mockMvc.perform(MockMvcRequestBuilders.get("/service/test/testController")
.accept(MediaType.APPLICATION_JSON)//返回值接收json
.header("Timestamp", "1496656373783")
.header("AppId", "1003"));
reaction.andExpect(MockMvcResultMatchers.status().isOk());
MvcResult mvcResult =reaction.andReturn();
System.out.println(mvcResult.getResponse().getContentAsString());
}
demo 2 有请求头、有请求体的post请求
样例代码如下:
@Test
public void 测试类() throws Exception {
PolicyInfoRequest request=new PolicyInfoRequest();
request.setAnnualPremium(100);
request.setPolicyNo("Test-222");
request.setPolicyRebate(0.28f);
request.setPolicyType(1);
request.setRebateAmount(28f);
String jsonRequest=JSON.toJSONString(request);
ResultActions reaction =this.mockMvc.perform(MockMvcRequestBuilders.post("/policy/info/save")
.contentType(MediaType.APPLICATION_JSON)//请求体时json
.header("Timestamp", "1496656373791")
.header("AppId", "1003")
.content(jsonRequest));
reaction.andExpect(MockMvcResultMatchers.status().isOk());
MvcResult mvcResult =reaction.andReturn();
System.out.println(mvcResult.getResponse().getContentAsString());
}
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。