springboot use mockMvc test controller

  In general, when we usually develop the project, if you want to enter the URL of the Controller test after editing the code, you need to restart the server, build http client for testing. This will make testing becomes very troublesome, for example, slow startup, testing and certification inconvenient, dependent on the network environment, this will cause the test can not be performed, in order to be tested Controller, it can be solved by introducing MockMVC.

  MockMvc realized simulation Http request can be directly used in the form of a network, switch to invoke the Controller so that the test speed can not rely on the network environment, but also provides a means of verification, so that the request may validate the tax and very convenient.

       MockMvcBuilder is used to construct MockMvc constructor which there are two implementations: StandaloneMockMvcBuilder and DefaultMockMvcBuilder, two test mode respectively, i.e. independent installation and integration testing Web environments (such embodiment not truly integrated web environment, and It is simulated by testing a corresponding Mock API, no need to start the server). For us, it can be used directly to create static factory MockMvcBuilders.

The following write a few simple cases, using a get request MockMvc test the Controller and post requests.

1. Introducing a jar package

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-test</artifactId>
  <scope>test</scope>
</dependency>

2. Write a test controller

/**
 * @author Sue
 * @create 2019-09-06 10:03
 **/
@RestController
@RequestMapping("/mock")
public class MockmvcController {

    /**
     * get请求
     * @param username
     * @param password
     * @return
     */
    @GetMapping("/getInfo")
    public R getInfo(String username,String password){
        System.out.println("username:" + username + "," + "password:" + password);
        return R.ok();
    }

    /**
     * post请求
     * @param username
     * @param password
     * @return
     */
    @PostMapping("/getInfo2")
    public R getInfo2(String username,String password){
        System.out.println("username:" + username + "," + "password:" + password);
        return R.ok();
    }

    /**
     * post请求接收json格式
     * @param user
     * @return
     */
    @PostMapping("/getInfo3")
    public R getInfo3(@RequestBody User user){
        System.out.println(user);
        return R.ok(user);
    }

}

3. Create a unit test

use the shortcut key idea ctrl + alt + t

@RunWith (SpringRunner.class) 
@SpringBootTest 
public class MockmvcTest { 
    // the ApplicationContext vessel injection web environment 
    @Autowired 
    Private the WebApplicationContext context; 
    / ** 
     * mvc simulation test object 
     * / 
    ; Private MockMvc mockMvc 

    / ** 
     * Before performing the test methods performing the method 
     * / 
    @Before annotation // this effect will again performed before each method 
    public void before () throws Exception { 
        // Get mockmvc object instance 
        mockMvc = MockMvcBuilders.webAppContextSetup (this.context) .build ( ) ; 
    } 

    @Test 
    public void getInfo () throws Exception { 
        mvcResult mvcResult mockMvc.perform = ( 
                MockMvcRequestBuilders.get ( "/ the mock / getInfo")
                        .accept(MediaType.APPLICATION_JSON)
                        .param("username", "Jack")
                        .param("password", "Jack001"))
                        .andExpect(MockMvcResultMatchers.status().isOk())
                        .andDo(MockMvcResultHandlers.print()).andReturn();
        System.out.println("输出 " + mvcResult.getResponse().getContentAsString());
    }

    @Test
    public void getInfo2() throws Exception {
        MvcResult mvcResult = mockMvc.perform(
                MockMvcRequestBuilders.post("/mock/getInfo2")
                        .accept(MediaType.APPLICATION_JSON)
                        .param("username", "Jack")
                        .param("password", "Jack001"))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andDo(MockMvcResultHandlers.print()).andReturn();
        System.out.println("输出 " + mvcResult.getResponse().getContentAsString());
    }

    @Test
    public void getInfo3() throws Exception {
        User user = new User();
        user.setUsername("Jack");
        user.setPassword("Jack001");
        String jsonString = JSON.toJSONString(user);
        MvcResult mvcResult = mockMvc.perform(
                MockMvcRequestBuilders.post("/mock/getInfo3")
                        .contentType(MediaType.APPLICATION_JSON)
                        .content(jsonString)
                        .accept(MediaType.APPLICATION_JSON)
                )
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andDo(MockMvcResultHandlers.print()).andReturn();

        int status = mvcResult.getResponse().getStatus();
        Assert.assertTrue("正确", status == 200);

        System.out.println("输出 " + mvcResult.getResponse().getContentAsString());
    }

}

Fourth, the test

Code analysis:

  • perform: Performing a RequestBuiderrequest, automate SpringMvcprocesses and mapped to the corresponding process performed by a controller
  • get: Declare a transmission getmethod request  public static MockHttpServletRequestBuilder get(String urlTemplate, Object... uriVars) { return new MockHttpServletRequestBuilder(HttpMethod.GET, urlTemplate, uriVars);}This is a static method, it can be directly imported, worth according to a template and uri uri variables getrequest method additionally provides methods other requests, such as: post, put, delete and the like.
  • andExperct: Add ResultMatchervalidation rules, the verification performresults of the implementation is completed correctly (determination of the returned data)
  • andDo: Add the ResultHandlerresults of the processor, such as debug print to the consoleprint()
  • andReturn: Returns the corresponding last MvcResultand custom authentication / asynchronous processing of the next step.

The entire testing process is as follows:

1, to prepare a test environment

2, through execution request MockMvc

3, add validation assertion

4, adding the result processor

5, to obtain MvcResult customize assert / asynchronous request the next step

6, uninstall the test environment

By these methods, I believe we have some understanding mockMvc test, if you want to use more detail, by the method name and parameters should be able to understand the meaning of the method, if you still can not understand, you can view the following official documents used in conjunction.

 

Official Documents 

reference

Guess you like

Origin www.cnblogs.com/sueyyyy/p/11534047.html