模拟HTTP请求调用controller

原文参考本人的简书:https://www.jianshu.com/p/0221edbe1598

MockMvc实现了对Http请求的模拟,能够直接使用网络的形式,转换到Controller调用,这样使得测试速度更快,不依赖网络环境。而且提供了一套验证的工具。代码如下:

 1 @RunWith(SpringRunner.class)
 2 @WebMvcTest(MyController.class)
 3 public class MyControllerTest {
 4   @Autowired
 5   private MockMvc mockMvc;
 6   /**
 7    * 测试方法
 8    */
 9   private void bindAndUnbindTenantPoiTest() throws Exception {
10     MvcResult mvcResult = mockMvc.perform(post(${"访问的url"})
11         .param("${key1}", "${value1}")
12         .param("${key2}", "${value2}")
13         .param("${key3}", "${value3}")) 
14         .andDo(print()) // 定义执行行为
15         .andExpect(status().isOk()) // 对请求结果进行验证
16         .andReturn(); // 返回一个MvcResult
17     jsonObject = toJsonObject(mvcResult);
18     assert jsonObject.getIntValue("code") == code; // 断言返回内容是否符合预期
19     assert message.equals(jsonObject.getString("message"));
20   }  
21 }
View Code

Perform介绍

perform用来调用controller业务逻辑,有postget等多种方法,具体可以参考利用Junit+MockMvc+Mockito对Http请求进行单元测试

Param

通过param添加请求参数,一个参数一个参数加或者通过params添加MultiValueMap<String, String>。parma部分源码如下:

/**
     * 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;
    }
View Code

写在后面

还有个坑就是使用注解的时候,看看注解之间是否有重叠,否则会报错。如果同时使用@WebMvcTest @Configuration就错了。具体可以查看注解源码

原文地址:https://www.cnblogs.com/lvmengtian/p/10485652.html