原文參考本人的簡書:https://www.jianshu.com/p/0221edbe1598git
MockMvc實現了對Http請求的模擬,可以直接使用網絡的形式,轉換到Controller調用,這樣使得測試速度更快,不依賴網絡環境。並且提供了一套驗證的工具。代碼以下:github
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用來調用controller業務邏輯,有post、get等多種方法,具體能夠參考利用Junit+MockMvc+Mockito對Http請求進行單元測試spring
經過param添加請求參數,一個參數一個參數加或者經過params添加MultiValueMap<String, String>。parma部分源碼以下:json
/** * 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就錯了。具體能夠查看註解源碼springboot