分類
發燒車訊

PowerMock學習(四)之Mock static的使用

我們編寫代碼的時候,總會寫一些工具類,為了方便調用喜歡使用static關鍵字來修飾對應方法。

那麼現在舉例說明,還是準備兩個接口,第一個是查詢學生總數,第二個是新增學生兩個接口,具體示例代碼如下:

package com.rongrong.powermock.mockstatic;

import com.rongrong.powermock.service.Student;

/**
 * @author rongrong
 * @version 1.0
 * @date 2019/11/23 8:08
 */
public class StudentStaticService {

    /**
     * 獲取學生總數
     * @return
     */
    public int getStudentTotal(){
        return StudentUtils.getStudent();
    }

    /**
     * 創建一個學生
     * @param student
     */
    public void createStudent(Student student){
        StudentUtils.createStudent(student);
    }
}

接着我們再來看看這個靜態工具類StudentUtils,具體代碼示例如下:

package com.rongrong.powermock.mockstatic;

import com.rongrong.powermock.service.Student;

/**
 * @author rongrong
 * @version 1.0
 * @date 2019/11/23 7:38
 */
public class StudentUtils {
    /**
     * 獲取學生總數
     * @return
     */
    public static int getStudent(){
        throw new UnsupportedOperationException();
    }

    /**
     * 創建一個學生
     * @param student
     */
    public static void createStudent(Student student){
        throw new UnsupportedOperationException();
    }
}

接下來我們用傳統方式,來做單元測試,示例代碼如下:

    @Test
    public void testGetStudnetTotal(){
        StudentStaticService staticService = new StudentStaticService();
        int studentTotal = staticService.getStudentTotal();
        assertEquals(studentTotal,10);
    }

    @Test
    public void testCreateStudent(){
        StudentStaticService staticService = new StudentStaticService();
        staticService.createStudent(new Student());
        assertTrue(true);
    }

接着運行下測試用例,結果肯定報錯了,為什麼報錯,這裏就不再細說了,參考之前文章,報錯,如下圖所示:

 

接下來我們使用powermock來進行測試,具體示例代碼如下:

 @Test
    public void testGetStudentWithMock(){
        //先mock工具類對象
        PowerMockito.mockStatic(StudentUtils.class);
        //模擬靜態類調用
        PowerMockito.when(StudentUtils.getStudent()).thenReturn(10);
        //構建service
        StudentStaticService service = new StudentStaticService();
        int studentTotal = service.getStudentTotal();
        assertEquals(10,studentTotal);
    }

    @Test
    public void testCreateStudentWithMock(){
        //先模擬靜態工具類
        PowerMockito.mockStatic(StudentUtils.class);
        //模擬調用
        PowerMockito.doNothing().when(StudentUtils.class);
        //構建service
        StudentStaticService service = new StudentStaticService();
        Student student = new Student();
        service.createStudent(student);
        //這裏用powermock來驗證,而不是mock,更體現了powermock的強大
        PowerMockito.verifyStatic();
    }

再次運行,測試通過,如下圖所示:

 

 

運行之前先讓powermock為我們準備了StudentUtils工具類,而且採用mockstatic的方法,最後我們用powermock.verifyStatic()驗證,而不是mock,更體現了powermock的強大。

 

本站聲明:網站內容來源於博客園,如有侵權,請聯繫我們,我們將及時處理【其他文章推薦】

USB CONNECTOR掌控什麼技術要點? 帶您認識其相關發展及效能

※評比前十大台北網頁設計台北網站設計公司知名案例作品心得分享

※智慧手機時代的來臨,RWD網頁設計已成為網頁設計推薦首選