MockMvc實現對Http請求的模擬,能夠方便對Controller進行測試,使得測試速度快、不依賴網絡環境,並且提供驗證的工具,使得請求的驗證統一併且很方便。html
二 常見使用方式java
1 MockMvcBuilder構造MockMvc的構造器web
2 MockMvcRequestBuilders建立請求requestspring
3 mockMvc調用perform,執行一個request請求,調用controller的業務處理邏輯,返回ResultActionsexpress
4 能夠經過ResultActions, MockMvcResultMatchers對結果進行驗證json
示例:api
@RunWith(SpringRunner.class) @SpringBootTest @TestExecutionListeners({ MockitoTestExecutionListener.class}) // 使用@MockBean, @SpyBean public abstract class AbstractBaseTest extends AbstractJUnit4SpringContextTests { protected static final Logger LOG = LogUtils.get(); } public class MockMvcDemo extends AbstractBaseTest { private MockMvc mvc; @Before public void setUp() { mvc = MockMvcBuilders.standaloneSetup(new AccountController()).build(); } @Test public void test() throws Exception { // 構建請求 MockHttpServletRequestBuilder request = MockMvcRequestBuilders.get("/account/info") .contentType("text/html") .accept(MediaType.APPLICATION_JSON); // 發送請求,獲取請求結果 ResultActions perform = mvc.perform(request); // 請求結果校驗 perform.andExpect(MockMvcResultMatchers.status().isOk()); MvcResult mvcResult = perform.andReturn(); MockHttpServletResponse response = mvcResult.getResponse(); // 校驗類:org.springframework.test.web.servlet.result.MockMvcResultMatchers } }
1 MockMvcBuilderspring-mvc
MockMvcBuilder是MockMvc的構造器,主要有兩個實現:StandaloneMockMvcBuilder和DefaultMockMvcBuilder。安全
① MockMvcBuilders.webAppContextSetup(WebApplicationContext context):集成Web環境方式,指定WebApplicationContext,將會從該上下文獲取相應的控制器並獲得相應的MockMvc;cookie
② MockMvcBuilders.standaloneSetup(Object... controllers):獨立測試方式,經過參數指定一組控制器,這樣就不須要從上下文獲取了,好比this.mockMvc =MockMvcBuilders.standaloneSetup(new AccountController()).build();
2 MockMvcRequestBuilders
MockMvcRequestBuilders用於構建請求,返回MockHttpServletRequestBuilder / MockMultipartHttpServletRequestBuilder ,
MockMvcRequestBuilders經常使用API:
MockHttpServletRequestBuilder get(String urlTemplate, Object... urlVariables):根據uri模板和uri變量值獲得一個GET請求方式的MockHttpServletRequestBuilder;如get(/user/{id}, 1L);
MockHttpServletRequestBuilder post(String urlTemplate, Object... urlVariables):同get相似,可是是POST方法;
MockHttpServletRequestBuilder put(String urlTemplate, Object... urlVariables):同get相似,可是是PUT方法;
MockHttpServletRequestBuilder delete(String urlTemplate, Object... urlVariables) :同get相似,可是是DELETE方法;
MockHttpServletRequestBuilder options(String urlTemplate, Object... urlVariables):同get相似,可是是OPTIONS方法;
MockHttpServletRequestBuilder request(HttpMethod httpMethod, String urlTemplate, Object... urlVariables): 提供本身的Http請求方法及uri模板和uri變量,如上API都是委託給這個API;
MockMultipartHttpServletRequestBuilder fileUpload(String urlTemplate, Object... urlVariables):提供文件上傳方式的請求,獲得MockMultipartHttpServletRequestBuilder;
RequestBuilder asyncDispatch(final MvcResult mvcResult):建立一個從啓動異步處理的請求的MvcResult進行異步分派的RequestBuilder;
MockHttpServletRequestBuilder經常使用API:
MockHttpServletRequestBuilder header(String name, Object... values)/MockHttpServletRequestBuilder headers(HttpHeaders httpHeaders):添加頭信息;
MockHttpServletRequestBuilder contentType(MediaType mediaType):指定請求的contentType頭信息;
MockHttpServletRequestBuilder accept(MediaType... mediaTypes)/MockHttpServletRequestBuilder accept(String... mediaTypes):指定請求的Accept頭信息;
MockHttpServletRequestBuilder content(byte[] content)/MockHttpServletRequestBuilder content(String content):指定請求Body體內容;
MockHttpServletRequestBuilder cookie(Cookie... cookies):指定請求的Cookie;
MockHttpServletRequestBuilder locale(Locale locale):指定請求的Locale;
MockHttpServletRequestBuilder characterEncoding(String encoding):指定請求字符編碼;
MockHttpServletRequestBuilder requestAttr(String name, Object value) :設置請求屬性數據;
MockHttpServletRequestBuilder sessionAttr(String name, Object value)/MockHttpServletRequestBuilder sessionAttrs(Map<string, object=""> sessionAttributes):設置請求session屬性數據;
MockHttpServletRequestBuilder flashAttr(String name, Object value)/MockHttpServletRequestBuilder flashAttrs(Map<string, object=""> flashAttributes):指定請求的flash信息,好比重定向後的屬性信息;
MockHttpServletRequestBuilder session(MockHttpSession session) :指定請求的Session;
MockHttpServletRequestBuilder principal(Principal principal) :指定請求的Principal;
MockHttpServletRequestBuilder contextPath(String contextPath) :指定請求的上下文路徑,必須以「/」開頭,且不能以「/」結尾;
MockHttpServletRequestBuilder pathInfo(String pathInfo) :請求的路徑信息,必須以「/」開頭;
MockHttpServletRequestBuilder secure(boolean secure):請求是否使用安全通道;
MockHttpServletRequestBuilder with(RequestPostProcessor postProcessor):請求的後處理器,用於自定義一些請求處理的擴展點;
MockMultipartHttpServletRequestBuilder繼承自MockHttpServletRequestBuilder,又提供了以下API:
MockMultipartHttpServletRequestBuilder file(String name, byte[] content)/MockMultipartHttpServletRequestBuilder file(MockMultipartFile file):指定要上傳的文件;
示例:
MockHttpServletRequestBuilder request = MockMvcRequestBuilders.get("/account/info")
.contentType("text/html")
.accept(MediaType.APPLICATION_JSON);
3 ResultActions
MockMvc.perform(RequestBuilder requestBuilder)調用後返回ResultActions:
ResultActions.andExpect:添加執行完成後的斷言。添加ResultMatcher驗證規則,驗證控制器執行完成後結果是否正確;
ResultActions.andDo:添加一個結果處理器,好比此處使用.andDo(MockMvcResultHandlers.print())輸出整個響應結果信息,能夠在調試的時候使用;
ResultActions.andReturn:表示執行完成後返回相應的結果,用於自定義驗證/下一步的異步處理;
4 ResultMatchers
ResultMatcher驗證匹配執行完請求後的結果,只有一個match(MvcResult result)斷言方法,若是匹配失敗將拋出相應的異常。
spring mvc測試框架提供了不少***ResultMatchers來知足測試需求,能夠經過MockMvcResultMatchers查看內置ResultMatcher。(注意:***ResultMatchers不是ResultMatcher的實現子類)
HandlerResultMatchers handler():請求的Handler驗證器,好比驗證處理器類型/方法名;此處的Handler其實就是處理請求的控制器;
RequestResultMatchers request():獲得RequestResultMatchers驗證器;
ModelResultMatchers model():獲得模型驗證器;
ViewResultMatchers view():獲得視圖驗證器;
FlashAttributeResultMatchers flash():獲得Flash屬性驗證;
StatusResultMatchers status():獲得響應狀態驗證器;
HeaderResultMatchers header():獲得響應Header驗證器;
CookieResultMatchers cookie():獲得響應Cookie驗證器;
ContentResultMatchers content():獲得響應內容驗證器;
JsonPathResultMatchers jsonPath(String expression, Object ... args)/ResultMatcher jsonPath(String expression, Matcher matcher):獲得Json表達式驗證器;
XpathResultMatchers xpath(String expression, Object... args)/XpathResultMatchers xpath(String expression, Map<string, string=""> namespaces, Object... args):獲得Xpath表達式驗證器;
ResultMatcher forwardedUrl(final String expectedUrl):驗證處理完請求後轉發的url(絕對匹配);
ResultMatcher forwardedUrlPattern(final String urlPattern):驗證處理完請求後轉發的url(Ant風格模式匹配,@since spring4);
ResultMatcher redirectedUrl(final String expectedUrl):驗證處理完請求後重定向的url(絕對匹配);
ResultMatcher redirectedUrlPattern(final String expectedUrl):驗證處理完請求後重定向的url(Ant風格模式匹配,@since spring4);
5 MvcResult
MvcResult爲執行完控制器後獲得的整個結果,並不單單是返回值,其包含了測試時須要的全部信息。
MockHttpServletRequest getRequest():獲得執行的請求;
MockHttpServletResponse getResponse():獲得執行後的響應;
Object getHandler():獲得執行的處理器,通常就是控制器;
HandlerInterceptor[] getInterceptors():獲得對處理器進行攔截的攔截器;
ModelAndView getModelAndView():獲得執行後的ModelAndView;
Exception getResolvedException():獲得HandlerExceptionResolver解析後的異常;
FlashMap getFlashMap():獲得FlashMap;
Object getAsyncResult()/Object getAsyncResult(long timeout):獲得異步執行的結果;
四 相關連接