1. 程式人生 > >Spring MVC學習總結(14)——SpringMVC測試框架之mockMVC詳解

Spring MVC學習總結(14)——SpringMVC測試框架之mockMVC詳解

SpringMVC測試框架
基於RESTful風格的SpringMVC的測試,我們可以測試完整的Spring MVC流程,即從URL請求到控制器處理,再到檢視渲染都可以測試。
一 MockMvcBuilder
MockMvcBuilder是用來構造MockMvc的構造器,其主要有兩個實現:StandaloneMockMvcBuilder和DefaultMockMvcBuilder,分別對應兩種測試方式,即獨立安裝和整合Web環境測試(此種方式並不會整合真正的web環境,而是通過相應的Mock API進行模擬測試,無須啟動伺服器)。對於我們來說直接使用靜態工廠MockMvcBuilders建立即可。
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進行測試;
2.獨立測試方式
MockMvcBuilders.standaloneSetup(Object... controllers):通過引數指定一組控制器,這樣就不需要從上下文獲取了;
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"));  
    }  
整個過程:
1、mockMvc.perform執行一個請求;
2、MockMvcRequestBuilders.get("/user/1")構造一個請求
3、ResultActions.andExpect新增執行完成後的斷言
4、ResultActions.andDo新增一個結果處理器,表示要對結果做點什麼事情,比如此處使用MockMvcResultHandlers.print()輸出整個響應結果資訊。
5、ResultActions.andReturn表示執行完成後返回相應的結果。
整個測試過程非常有規律:
1、準備測試環境
2、通過MockMvc執行請求
3.1、新增驗證斷言
3.2、新增結果處理器
3.3、得到MvcResult進行自定義斷言/進行下一步的非同步請求
4、解除安裝測試環境
三 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"));