呼叫mock物件的方法時,不會執行真實的方法,而是傳回類型的預設值,如object回傳null, int回傳0等,否則透過指定when (方法).thenReturn(value)來指定方法的回傳值。同時mock物件可以進行追蹤,使用verify方法看是否已經被呼叫過。而spy對象,預設會執行真實方法,返回值可以透過when.thenReturn進行覆寫。可見mock只要避開了執行一些方法,直接回傳指定的值,方便做其他測試。
需要的依賴
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> <version>2.23.4</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-test</artifactId> <version>2.1.13.RELEASE</version> </dependency>
程式碼範例
@RunWith(MockitoJUnitRunner.class) @SpringBootTest() public class StudentServiceTest { @InjectMocks StudentService studentService = new StudentServiceImpl(); @Mock StudentDAO studentDAO; @Before public void before(){ Mockito.doReturn(new StudentDO("张三", 18)).when(studentDAO).read(Mockito.anyString()); } @Test public void testRead(){ StudentDO read = studentService.read(""); Assert.assertNotNull(read); } }
需要的依賴
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>5.1.14.RELEASE</version> </dependency> <dependency> <groupId>com.jayway.jsonpath</groupId> <artifactId>json-path</artifactId> <version>2.4.0</version> </dependency>
程式碼範例
@RunWith(MockitoJUnitRunner.class) @SpringBootTest() public class StudentControllerTest { @Resource MockMvc mockMvc; @InjectMocks StudentController studentController; @Mock StudentService studentService; @Before public void before() { mockMvc = MockMvcBuilders.standaloneSetup(studentController).build(); Mockito.doReturn(new StudentDO("张三", 18)).when(studentService).read(Mockito.anyString()); } @Test public void testRead() throws Exception { MockHttpServletRequestBuilder request = MockMvcRequestBuilders.get("/student/read/1"); mockMvc.perform(request) .andDo(print()) .andExpect(status().isOk()) .andExpect(jsonPath("$.name").value("张三")); } }
以上是Java單元測試Mockito如何用的詳細內容。更多資訊請關注PHP中文網其他相關文章!