Java單元測試Mockito的使用詳解

Mockito簡介

    調用mock對象的方法時,不會執行真實的方法,而是返回類型的默認值,如object返回null, int返回0等,否則通過指定when(方法).thenReturn(value)來指定方法的返回值。同時mock對象可以進行跟蹤,使用verify方法看是否已經被調用過。而spy對象,默認會執行真實方法,返回值可以通過when.thenReturn進行覆蓋。可見mock隻要避開瞭執行一些方法,直接返回指定的值,方便做其他測試。

Service測試用例

需要的依賴

  <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);
    }
}

Controller測試用例

需要的依賴

<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("張三"));
    }

}

到此這篇關於單元測試-Mockito的使用的文章就介紹到這瞭,更多相關單元測試 Mockito使用內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: