原文參考本人的簡書: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 }
Perform介紹
perform用來調用controller業務邏輯,有post、get等多種方法,具體可以參考利用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; }
寫在后面
還有個坑就是使用注解的時候,看看注解之間是否有重疊,否則會報錯。如果同時使用@WebMvcTest @Configuration就錯了。具體可以查看注解源碼