MockMvc implements the simulation of Http requests and can directly use the network form to convert to the Controller call. This makes the test fast and independent of the network environment, and provides a set of validation tools. This makes validation of requests uniform and convenient, and most convenient for customer testing, testing our Rest Api without having to start the server.

SpringMVC writes Rest examples

The Controller sample

@Controller
@RequestMapping(value = "/test")
public class TestWebController {

    @ResponseBody
    @RequestMapping(value = "/list", method = {RequestMethod.GET})
    public List getMock(@RequestParam(name = "id", required = false, defaultValue = "l0") String id) {
        return Arrays.asList("l1"."l2"."l3", id);
    }

    @ResponseBody
    @RequestMapping(value = "/pust", method = {RequestMethod.POST})
    public Object postMock(@RequestBody Object data) {
        return ImmutableMap.<String, String>builder().put("data", JSON.toJSONString(data)).build();
    }
	
	 @RequestMapping(value = "/view", method = {RequestMethod.GET})
    public ModelAndView viewMock(a){
        return new ModelAndView("index"); }}Copy the code

MockMvc tests the Rest sample

  1. MockMvc basic interaction example
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:context/spring-context.xml"."classpath:context/spring-mvc.xml"})
@WebAppConfiguration(value = "src/main/webapp")
public class TestController {

    private MockMvc mockMvc;

    @Autowired
    private WebApplicationContext webApplicationContext;

    @Before
    public void setUp(a) throws Exception {
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    }

    @Test
    public void test01(a) throws Exception {
        MvcResult mvcResult = this.mockMvc.perform(MockMvcRequestBuilders.get("/test/list")
                .cookie(new Cookie("token"."F3AF5F1D14F534F677XF3A00E352C"))   // Login authorization
                .accept(MediaType.parseMediaType("application/json; charset=UTF-8")))
                .andExpect(handler().handlerType(TestWebController.class))  // Verify the type of controller executed
                .andExpect(handler().methodName("getMock"))                 // Verify the name of the method executed
                .andExpect(status().isOk())                                 // Verify execution status
                .andDo(print())                                             // Prints the interaction information.andReturn(); System.out.println(mvcResult.getResponse().getContentAsString()); }}Copy the code

MockMvc can simulate a call to a Controller; MockMvc. Perform perform a request; 2, MockMvcRequestBuilders. Get (urlTemplate, 4. ResultActions. AndDo Adds a result handler to indicate that you want to do something with the result. Such as used here MockMvcResultHandlers. Print () output the response information. 5. ResultActions. AndReturn Indicates that corresponding results are returned after execution.

Execution Result:

["l1"."l2"."l3"."l0"]
Copy the code

Interactive information:

MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /test/list
       Parameters = {}
          Headers = {Accept=[application/json;charset=UTF-8]}

Handler:
             Type = com.simple.example.web.TestWebController
           Method = public java.util.List com.simple.example.web.TestWebController.getMock(java.lang.String)

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 = ["l1"."l2"."l3"."l0"]
    Forwarded URL = null
   Redirected URL = null
          Cookies = []
Copy the code
  1. MockMvc request parameter example
@Test
    public void test02(a) throws Exception {
        MvcResult mvcResult = mockMvc.perform(get("/test/list? id={id}"."Template parameters")
                .accept(MediaType.parseMediaType("application/json; charset=UTF-8")))
                .andExpect(handler().handlerType(TestWebController.class))  // Verify the type of controller executed
                .andExpect(handler().methodName("getMock"))                 // Verify the name of the method executed
                .andExpect(status().isOk())                                 // Verify execution status
                .andDo(print())                                             // Prints the interaction information
                .andReturn();
        System.out.println(mvcResult.getResponse().getContentAsString());
    }
Copy the code

Execution Result:

["l1"."l2"."l3"."Template parameters"]
Copy the code
  1. MockMvc tests the Post example
@Test
public void test(a) throws Exception {
   MvcResult mvcResult = mockMvc.perform(post("/test/pust")
                .contentType(MediaType.APPLICATION_JSON)
                .content(JSON.toString(Arrays.asList("p1"."p2")))
                .accept(MediaType.parseMediaType("application/json; charset=UTF-8")))
                .andExpect(handler().handlerType(TestWebController.class))  // Verify the type of controller executed
                .andExpect(handler().methodName("getMock"))                 // Verify the name of the method executed
                .andExpect(status().isOk())                                 // Verify execution status
                .andDo(print())                                             // Prints the interaction information
                .andReturn();
        System.out.println(mvcResult.getResponse().getContentAsString());
}
Copy the code

Mutual information

MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /test/pust
       Parameters = {}
          Headers = {Content-Type=[application/json], Accept=[application/json;charset=UTF-8]}

Handler:
             Type = com.simple.example.web.TestWebController
           Method = public java.lang.Object com.simple.example.web.TestWebController.postMock(java.lang.Object)

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 = {"data":"[\"p1\",\"p2\"]"}
    Forwarded URL = null
   Redirected URL = null
          Cookies = []
Copy the code

Execution Result:

{"data":"[\"p1\",\"p2\"]"}
Copy the code
  1. Test View page
@Test
public void test05(a) throws Exception {
   MvcResult mvcResult = mockMvc.perform(get("/test/view"))
           .andExpect(view().name("index"))  // Validate the view page
           .andExpect(model().hasNoErrors()) // Verify that the page has no errors
           .andExpect(status().isOk())       // Verify the status code
           .andDo(print())
           .andReturn();
   System.out.println(mvcResult.getModelAndView().getViewName());
}
Copy the code

Execution Result:

index
Copy the code

MockMvc in-depth study

  • Docs. Spring. IO/spring – secu…
  • Jinnianshilongnian.iteye.com/blog/200466…