1. 程式人生 > >PowerMock學習(四)之Mock static的使用

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

&n