mock(模擬)
依賴於spring的框架和spring的環境
切片測試:指用mockmvc測試controller層,模擬返回service層的值,將層與層間的聯系斷開。
集成測試:指用mockmvc測試controller層,但不間隔service層。將controller層和service層集合起來測試。
java的單元測試框架有junit、mockMvc等
java的mock框架一般有Mockito、EasyMock、powerMock等(框架用來提供mock的工具,用於mock的打樁和斷言)
springMVC的測試中,一般采用mockMvc+Mockito的組合來進行mock模擬測試
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,classes = Application.class)
@ContextConfiguration(loader = SpringBootContextLoaderEx.class) public class ControllerTestJuint extends BaseJunit{ private MockMvc mockMvc; @Autowired protected WebApplicationContext wac; // mock的對象,stationService被mockbean注解之后,會自己注入到容器當中,stationService中的所有方法除開被打樁返回的,其余調用時,都返回null @MockBean private StationService stationService; @Before() //這個方法在每個方法執行之前都會執行一遍 public void setup() { mockMvc = MockMvcBuilders.webAppContextSetup(wac).build(); //初始化MockMvc對象 SecurityUtils.setSecurityManager(wac.getBean(SecurityManager.class); }
@Test public void mockTest() throws Exception{ // 打樁,給指定方法返回值 when(stationService.add(any(),any())).thenReturn(true); // 給返回值為void的方法打樁 doNothing.when(stationService).updateService(any()); ResultActions reaction = this.mockMvc.perform(MockMvcRequestBuilders.post("/sys/out/mockTest") .contentType(MediaType.APPLICATION_JSON)//請求體時json .param("customerId","7") .param("serviceType","all_service") .param("params[company_id]","1110000")//組裝map對象 .param("params[AGE]","0,5")) .anddo(MockMvcResultHandlers.print()) // 控制台打印出請求體 ); reaction.andExpect(MockMvcResultMatchers.status().isOk()); MvcResult mvcResult =reaction.andReturn(); System.out.println(mvcResult.getResponse().getContentAsString()); TimeUnit.SECONDS.sleep(60*60); } }
thenReturn 中可以指定多個返回值。在調用時返回值依次出現。若調用次數超過返回值的數量,再次調用時返回最后一個返回值
mockito不支持對靜態(static)方法進行打樁。可以使用PowerMock對靜態方法進行打樁
PowerMockito.mockStatic(AmountUtil.class);
PowerMockito.when(AmountUtil.CustomFormatWith2Digits(anyInt())).thenReturn("zzzz");
對mvc的controller層進行測試,使用Mockmvc
對普通方法進行單元測試,使用junit
普通方法也能進行mock,使用junit+mockitor
普通方法測試:
@Test public void testBubbleSort() { Node node1 = new Node(1); Node node2 = new Node(2); Node node3 = new Node(3); Node[] nodes = {node1,node2,node3}; bubbleSort.bubbleSort(nodes); Assert.assertEquals(3, nodes[0].getValue()); // 斷言,驗證測試的正確性 Assert.assertEquals(2, nodes[1].getValue()); Assert.assertEquals(1, nodes[2].getValue()); }
mockitor 可以使用verify來驗證方法的調用次數