來自:http://www.cnblogs.com/lyy-2016/p/6122144.html(尊重版權)html
SpringMVC測試框架web
基於RESTful風格的SpringMVC的測試,咱們能夠測試完整的Spring MVC流程,即從URL請求到控制器處理,再到視圖渲染均可以測試。spring
一 MockMvcBuilderexpress
MockMvcBuilder是用來構造MockMvc的構造器,其主要有兩個實現:StandaloneMockMvcBuilder和DefaultMockMvcBuilder,分別對應兩種測試方式,即獨立安裝和集成Web環境測試(此種方式並不會集成真正的web環境,而是經過相應的Mock API進行模擬測試,無須啓動服務器)。對於咱們來講直接使用靜態工廠MockMvcBuilders建立便可。json
1.集成Web環境方式安全
MockMvcBuilders.webAppContextSetup(WebApplicationContext context):指定WebApplicationContext,將會從該上下文獲取相應的控制器並獲得相應的MockMvc;服務器
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:config/IncotermsRestServiceTest-context.xml") @WebAppConfiguration public class IncotermsRestServiceTest { @Autowired private WebApplicationContext wac; private MockMvc mockMvc; @Before public void setup() { this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); //構造MockMvc } ... }
注意:
(1)@WebAppConfiguration:測試環境使用,用來表示測試環境使用的ApplicationContext將是WebApplicationContext類型的;value指定web應用的根;
(2)經過@Autowired WebApplicationContext wac:注入web環境的ApplicationContext容器;
(3)而後經過MockMvcBuilders.webAppContextSetup(wac).build()建立一個MockMvc進行測試;cookie
2.獨立測試方式session
MockMvcBuilders.standaloneSetup(Object... controllers):經過參數指定一組控制器,這樣就不須要從上下文獲取了;mvc
public class PricingExportResultsRestServiceTest { @InjectMocks private PricingExportResultsRestService pricingExportResultsRestService; @Mock private ExportRateScheduleService exportRateScheduleService; @Mock private PricingUrlProvider pricingUrlProvider; private MockMvc mockMvc; @Before public void setup() { MockitoAnnotations.initMocks(this); mockMvc = MockMvcBuilders.standaloneSetup(pricingExportResultsRestService).build(); //構造MockMvc } ... }
主要是兩個步驟:
(1)首先本身建立相應的控制器,注入相應的依賴
(2)經過MockMvcBuilders.standaloneSetup模擬一個Mvc測試環境,經過build獲得一個MockMvc
二 MockMvc
先看一個測試例子1:
@Test public void createIncotermSuccess() throws Exception { IncotermTo createdIncoterm = new IncotermTo(); createdIncoterm.setId(new IncotermId(UUID.fromString("6305ff33-295e-11e5-ae37-54ee7534021a"))); createdIncoterm.setCode("EXW"); createdIncoterm.setDescription("code exw"); createdIncoterm.setLocationQualifier(LocationQualifier.DEPARTURE); when(inventoryService.create(any(IncotermTo.class))).thenReturn(createdIncoterm); mockMvc.perform(post("/secured/resources/incoterms/create").accept(MediaType.APPLICATION_JSON).contentType(MediaType.APPLICATION_JSON) .content("{\"code\" : \"EXW\", \"description\" : \"code exw\", \"locationQualifier\" : \"DEPARTURE\"}".getBytes())) //.andDo(print()) .andExpect(status().isOk()) .andExpect(jsonPath("id.value").exists()) .andExpect(jsonPath("id.value").value("6305ff33-295e-11e5-ae37-54ee7534021a")) .andExpect(jsonPath("code").value("EXW")); }
perform:執行一個RequestBuilder請求,會自動執行SpringMVC的流程並映射到相應的控制器執行處理;
andExpect:添加ResultMatcher驗證規則,驗證控制器執行完成後結果是否正確;
andDo:添加ResultHandler結果處理器,好比調試時打印結果到控制檯;
andReturn:最後返回相應的MvcResult;而後進行自定義驗證/進行下一步的異步處理;
看一個具體的例子2:
@Test public void testView() throws Exception { MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get("/user/1")) .andExpect(MockMvcResultMatchers.view().name("user/view")) .andExpect(MockMvcResultMatchers.model().attributeExists("user")) .andDo(MockMvcResultHandlers.print()) .andReturn(); Assert.assertNotNull(result.getModelAndView().getModel().get("user")); }
整個過程:
一、mockMvc.perform執行一個請求;
二、MockMvcRequestBuilders.get("/user/1")構造一個請求
三、ResultActions.andExpect添加執行完成後的斷言
四、ResultActions.andDo添加一個結果處理器,表示要對結果作點什麼事情,好比此處使用MockMvcResultHandlers.print()輸出整個響應結果信息。
五、ResultActions.andReturn表示執行完成後返回相應的結果。
整個測試過程很是有規律:
一、準備測試環境
二、經過MockMvc執行請求
3.一、添加驗證斷言
3.二、添加結果處理器
3.三、獲得MvcResult進行自定義斷言/進行下一步的異步請求
四、卸載測試環境
三 RequestBuilder/MockMvcRequestBuilders
從名字能夠看出,RequestBuilder用來構建請求的,其提供了一個方法buildRequest(ServletContext servletContext)用於構建MockHttpServletRequest;其主要有兩個子類MockHttpServletRequestBuilder和MockMultipartHttpServletRequestBuilder(如文件上傳使用),即用來Mock客戶端請求須要的全部數據。
1.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;
2.MockHttpServletRequestBuilder和MockMultipartHttpServletRequestBuilder API
(1)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):請求的後處理器,用於自定義一些請求處理的擴展點;
(2)MockMultipartHttpServletRequestBuilder繼承自MockHttpServletRequestBuilder,又提供了以下API
MockMultipartHttpServletRequestBuilder file(String name, byte[] content)/MockMultipartHttpServletRequestBuilder file(MockMultipartFile file):指定要上傳的文件;
四 ResultActions
調用MockMvc.perform(RequestBuilder requestBuilder)後將獲得ResultActions,經過ResultActions完成以下三件事:
ResultActions andExpect(ResultMatcher matcher) :添加驗證斷言來判斷執行請求後的結果是不是預期的;
ResultActions andDo(ResultHandler handler) :添加結果處理器,用於對驗證成功後執行的動做,如輸出下請求/結果信息用於調試;
MvcResult andReturn() :返回驗證成功後的MvcResult;用於自定義驗證/下一步的異步處理;
五 ResultMatcher/MockMvcResultMatchers
1.ResultMatcher用來匹配執行完請求後的結果驗證,其就一個match(MvcResult result)斷言方法,若是匹配失敗將拋出相應的異常;spring mvc測試框架提供了不少***ResultMatchers來知足測試需求。注意這些***ResultMatchers並非ResultMatcher的子類,而是返回ResultMatcher實例的。Spring mvc測試框架爲了測試方便提供了MockMvcResultMatchers靜態工廠方法方便操做;
2.具體的API以下:
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);
六 一些經常使用的測試
1.測試普通控制器
mockMvc.perform(get("/user/{id}", 1)) //執行請求 .andExpect(model().attributeExists("user")) //驗證存儲模型數據 .andExpect(view().name("user/view")) //驗證viewName .andExpect(forwardedUrl("/WEB-INF/jsp/user/view.jsp"))//驗證視圖渲染時forward到的jsp .andExpect(status().isOk())//驗證狀態碼 .andDo(print()); //輸出MvcResult到控制檯
2.獲得MvcResult自定義驗證
MvcResult result = mockMvc.perform(get("/user/{id}", 1))//執行請求 .andReturn(); //返回MvcResult Assert.assertNotNull(result.getModelAndView().getModel().get("user")); //自定義斷言
3.驗證請求參數綁定到模型數據及Flash屬性
mockMvc.perform(post("/user").param("name", "zhang")) //執行傳遞參數的POST請求(也能夠post("/user?name=zhang")) .andExpect(handler().handlerType(UserController.class)) //驗證執行的控制器類型 .andExpect(handler().methodName("create")) //驗證執行的控制器方法名 .andExpect(model().hasNoErrors()) //驗證頁面沒有錯誤 .andExpect(flash().attributeExists("success")) //驗證存在flash屬性 .andExpect(view().name("redirect:/user")); //驗證視圖
4.文件上傳
byte[] bytes = new byte[] {1, 2}; mockMvc.perform(fileUpload("/user/{id}/icon", 1L).file("icon", bytes)) //執行文件上傳 .andExpect(model().attribute("icon", bytes)) //驗證屬性相等性 .andExpect(view().name("success")); //驗證視圖
5.JSON請求/響應驗證
String requestBody = "{\"id\":1, \"name\":\"zhang\"}"; mockMvc.perform(post("/user") .contentType(MediaType.APPLICATION_JSON).content(requestBody) .accept(MediaType.APPLICATION_JSON)) //執行請求 .andExpect(content().contentType(MediaType.APPLICATION_JSON)) //驗證響應contentType .andExpect(jsonPath("$.id").value(1)); //使用Json path驗證JSON 請參考http://goessner.net/articles/JsonPath/ String errorBody = "{id:1, name:zhang}"; MvcResult result = mockMvc.perform(post("/user") .contentType(MediaType.APPLICATION_JSON).content(errorBody) .accept(MediaType.APPLICATION_JSON)) //執行請求 .andExpect(status().isBadRequest()) //400錯誤請求 .andReturn(); Assert.assertTrue(HttpMessageNotReadableException.class.isAssignableFrom(result.getResolvedException().getClass()));//錯誤的請求內容體
6.異步測試
//Callable MvcResult result = mockMvc.perform(get("/user/async1?id=1&name=zhang")) //執行請求 .andExpect(request().asyncStarted()) .andExpect(request().asyncResult(CoreMatchers.instanceOf(User.class))) //默認會等10秒超時 .andReturn(); mockMvc.perform(asyncDispatch(result)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.id").value(1));
7.全局配置
mockMvc = webAppContextSetup(wac) .defaultRequest(get("/user/1").requestAttr("default", true)) //默認請求 若是其是Mergeable類型的,會自動合併的哦mockMvc.perform中的RequestBuilder .alwaysDo(print()) //默認每次執行請求後都作的動做 .alwaysExpect(request().attribute("default", true)) //默認每次執行後進行驗證的斷言 .build(); mockMvc.perform(get("/user/1")) .andExpect(model().attributeExists("user"));