可参考本人简书:模拟HTTP请求调用controllergit
MockMvc实现了对Http请求的模拟,可以直接使用网络的形式,转换到Controller调用,这样使得测试速度更快,不依赖网络环境。并且提供了一套验证的工具。github
单测代码以下:spring
@RunWith(SpringRunner.class) @WebMvcTest(MyController.class) public class MyControllerTest { @Autowired private MockMvc mockMvc; /** * 测试方法 */ private void bindAndUnbindTenantPoiTest() throws Exception { MvcResult mvcResult = mockMvc.perform(post(${"访问的url"}) .param("${key1}", "${value1}") .param("${key2}", "${value2}") .param("${key3}", "${value3}")) .andDo(print()) // 定义执行行为 .andExpect(status().isOk()) // 对请求结果进行验证 .andReturn(); // 返回一个MvcResult jsonObject = toJsonObject(mvcResult); assert jsonObject.getIntValue("code") == code; // 断言返回内容是否符合预期 assert message.equals(jsonObject.getString("message")); } }
perform用来调用controller业务逻辑,有post、get等多种方法,具体能够参考利用Junit+MockMvc+Mockito对Http请求进行单元测试json
经过param添加http的请求参数,格式是K-V,一个参数一个参数添加或者经过params添加MultiValueMap<String, String>。parma部分源码以下:springboot
/** * 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; }
还有个坑就是使用注解的时候,看看注解之间是否有重叠,不然会报错。若是同时使用@WebMvcTest @Configuration就错了。具体能够查看注解源码网络