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的強大。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM