Simulate HTTP request to call controller

Keywords: Java network Junit

Please refer to my brief book: Simulate HTTP request to call controller

Written in front

MockMvc realizes the simulation of Http request, and can directly use the form of network to convert to Controller call, which makes the test faster and does not depend on the network environment. It also provides a set of verification tools.

The single test code is as follows:

@RunWith(SpringRunner.class)
@WebMvcTest(MyController.class)
public class MyControllerTest {
  @Autowired
  private MockMvc mockMvc;
  /**
   * test method
   */
  private void bindAndUnbindTenantPoiTest() throws Exception {
    MvcResult mvcResult = mockMvc.perform(post(${"Visiting url"})
        .param("${key1}", "${value1}")
        .param("${key2}", "${value2}")
        .param("${key3}", "${value3}")) 
        .andDo(print()) // Define execution behavior
        .andExpect(status().isOk()) // Verify request results
        .andReturn(); // Return a MvcResult
    jsonObject = toJsonObject(mvcResult);
    assert jsonObject.getIntValue("code") == code; // Assert whether the returned content is as expected
    assert message.equals(jsonObject.getString("message"));
  }  
}

About Perform

perform is used to call controller business logic, including post, get and other methods. For details, please refer to Unit test of Http request with Junit+MockMvc+Mockito

Parameter Param introduction

Add http request parameters through param in the form of K-V. add one parameter for one parameter or add multivaluemap < string, string > through params. The source code of parma is as follows:

/**
     * Add a request parameter to the {@link MockHttpServletRequest}.
     * <p>If called more than once, new values get added to existing ones.
     * @param name the parameter name
     * @param values one or more values
     */
    public MockHttpServletRequestBuilder param(String name, String... values) {
        addToMultiValueMap(this.parameters, name, values);
        return this;
    }

    /**
     * Add a map of request parameters to the {@link MockHttpServletRequest},
     * for example when testing a form submission.
     * <p>If called more than once, new values get added to existing ones.
     * @param params the parameters to add
     * @since 4.2.4
     */
    public MockHttpServletRequestBuilder params(MultiValueMap<String, String> params) {
        for (String name : params.keySet()) {
            for (String value : params.get(name)) {
                this.parameters.add(name, value);
            }
        }
        return this;
    }

Written in the back

Another pit is to see if there is any overlap between annotations when using annotations, otherwise an error will be reported. If you use @ WebMvcTest @Configuration at the same time, you are wrong. See the annotation source code for details

Posted by Stoned Gecko on Tue, 03 Dec 2019 01:17:34 -0800