Use MockMvc to test SpringMVC Controller
MockMvc is a testing tool provided by springTest for SpringMvc. This allows unit testing to go beyond testing the Dao and Service layers. At the same time, you can test the Controller layer. Rich unit testing capabilities. There is no need to restart the servlet container frequently during testing, which simplifies the testing operation.
MockMvc requires ServletContext to simulate the user's request and response.
First choice, you need to add an Annotation to the test class header
@ WebAppConfiguration@RunWith (SpringJUnit4Cla***unner.class) @ ContextConfiguration (locations = {"classpath:spring/applicationContext.xml"})
@ WebAppConfiguration is used to introduce servletContext
Then you can write the test class in junit.
Demo 1 get request with request headers and no parameters
The sample code is as follows:
@ Test public void test class () throws Exception {ResultActions reaction=this.mockMvc.perform (MockMvcRequestBuilders.get ("/ service/test/testController") .accept (MediaType.APPLICATION_JSON) / / return value receives json .head er ("Timestamp", "1496656373783") .header ("AppId") "1003")) Reaction.andExpect (MockMvcResultMatchers.status (). IsOk ()); MvcResult mvcResult = reaction.andReturn (); System.out.println (mvcResult.getResponse (). GetContentAsString ());}
Demo 2 post request with request header and request body
The sample code is as follows:
@ Test public void Test Class () 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) / / request body json .header ("Timestamp", "1496656373791") .header ("AppId") "1003") .content (jsonRequest)) Reaction.andExpect (MockMvcResultMatchers.status (). IsOk ()); MvcResult mvcResult = reaction.andReturn (); System.out.println (mvcResult.getResponse (). GetContentAsString ());}
The above two examples can basically cover the need to use springtest's MockMvc for unit testing of Controller.