MockMvc 是springTest提供的对SpringMvc提供的测试工具。这样可以让单元测试不仅仅局限于对Dao和Service 层的测试。同时,也可以测试Controller层。丰富的单元测试的功能。测试时不用频繁重启servlet容器,简化了测试操作。

MockMvc需要ServletContext来模拟用户的请求和相应。

首选,需要在测试类头部添加一下Annotation

@WebAppConfiguration@RunWith(SpringJUnit4Cla***unner.class)@ContextConfiguration(locations = { "classpath:spring/applicationContext.xml" })

@WebAppConfiguration 用来引入servletContext

接下来就可以在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());	}

以上两个例子就能基本覆盖解决使用springtest的MockMvc对Controller进行单元测试的需求。