亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Java單元測試Mockito的使用詳解

 更新時間:2021年07月07日 15:09:13   作者:一簑煙雨  
Mockito是一個強(qiáng)大的mock工具,本文將重點(diǎn)講述Mockito的基本使用及注意事項(xiàng),以及Controller測試用例,本文通過示例代碼給大家介紹的非常詳細(xì),需要的朋友參考下吧

Mockito簡介

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

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

}

到此這篇關(guān)于單元測試-Mockito的使用的文章就介紹到這了,更多相關(guān)單元測試 Mockito使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論