1. Mock測試介紹
- 定義
在單元測試過程中,對於某些不容易構造或者不容易獲取的對象,用一個虛擬對象來創建以便測試的方法。 - 為什么使用mock測試
- 避免模塊開發之間的耦合;
- 輕量、簡便、靈活;
2. MockMVC介紹
基於RESTful風格的SpringMVC單元測試,可以測試完整的SpringMVC流程,即從URL請求到控制處理器,帶到視圖渲染都可以測試。
2.1 MockMvc
- 服務器端SpringMVC測試的主入口點。
- 通過MockMVCBuilders建造者的靜態方法去建造MockMVCBuilder,MockMvc由MockMVCBuilder構造。
- 核心方法:perform(RequestBuilder rb),執行一個RequestBuilder請,會自動執行SpringMVC的流程並映射到相應的控制器執行處理,該方法的返回值是一個ResultActions。
2.2 MockMVCBuilder
- MockMVCBuilder是使用構造者模式來構造MockMvc的構造器。
- 主要有兩個實現:StandaloneMockMvcBuilder和DefaultMockMvcBuilder。
- 可以直接使用靜態工廠MockMvcBuilders創建即可,不需要直接使用上面兩個實現類。
2.3 MockMVCBuilders
- 負責創建MockMVCBuilder對象。
- 有兩種創建方式
- standaloneSetup(Object... controllers): 通過參數指定一組控制器,這樣就不需要從上下文獲取了。
- webAppContextSetup(WebApplicationContext wac):指定WebApplicationContext,將會從該上下文獲取相應的控制器並得到相應的MockMvc
2.4 MockMvcRequestBuilders
- 用來構建Request請求的。
- 其主要有兩個子類MockHttpServletRequestBuilder和MockMultipartHttpServletRequestBuilder(如文件上傳使用),即用來Mock客戶端請求需要的所有數據。
2.5 ResultActions
- andExpect:添加ResultMatcher驗證規則,驗證控制器執行完成后結果是否正確。
- andDo:添加ResultHandler結果處理器,比如調試時打印結果到控制台。
- andReturn:最后返回相應的MvcResult;然后進行自定義驗證/進行下一步的異步處理。
- MockMvcResultMatchers
- 用來匹配執行完請求后的**結果驗證。
- 果匹配失敗將拋出相應的異常。
- 包含了很多驗證API方法。
- MockMvcResultHandlers
- 結果處理器,表示要對結果做點什么事情。
- 比如此處使用MockMvcResultHandlers.print()輸出整個響應結果信息。
2.6 MvcResult
單元測試執行結果,可以針對執行結果進行自定義驗證邏輯。采用斷言驗證數據。
代碼如下:
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.json.JSONArray; import org.json.JSONObject; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import com.boke.Application; /** * 演示MockMVC使用 * @author zenglingsheng */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration @WebAppConfiguration @SpringBootTest(classes=Application.class) public class NewApiControllerTest { private MockMvc mockMvc; @Autowired private WebApplicationContext webApplicationContext; @Before public void setUp() throws Exception { mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); } @Test public void testEquipmenttypes() throws Exception { MvcResult authResult = null; authResult = mockMvc.perform(get("/api/workitem/equipmenttypes")//使用get方式來調用接口。 .contentType(MediaType.APPLICATION_XHTML_XML)//請求參數的類型 .param("sessionid", "ZlbpLxXw")//請求的參數(可多個) ).andExpect(status().isOk()) .andReturn(); //獲取數據 JSONObject jsonObject =new JSONObject(authResult.getResponse().getContentAsString()); JSONArray jsonArrayData = (JSONArray)jsonObject.get("data"); //獲取第一個Array中的值,判斷查詢到的結果。 JSONObject jsonObject_data = null; if(jsonArrayData.length()>0){ jsonObject_data = (JSONObject) jsonArrayData.get(0); } //加斷言,判斷屬性值的問題。 Assert.assertNotNull(jsonObject.get("error_code")); Assert.assertEquals(jsonObject.get("error_code"),0); Assert.assertNotNull(jsonObject.get("error_msg")); Assert.assertEquals(jsonObject.get("error_msg"),"操作成功"); Assert.assertNotNull(jsonObject.get("data")); Assert.assertNotNull(jsonObject_data); Assert.assertEquals(jsonObject_data.get("equipmentty"),1); Assert.assertEquals(jsonObject_data.get("equipmenttypename"),"xxxxx"); } }
這是根據項目所測試的具體格式,測試數據時,測試到數據的最底層。萌新一枚,大神勿噴。
關聯文章:https://www.jianshu.com/p/94e5de3f28c9