TestNG中使用PowerMockito模擬靜態方法


在編寫單元測試的時候,常常需要模擬靜態方法。例如一個測試方法依賴於一個執行遠程調用的靜態方法,如果不模擬靜態方法,就可能需要准備遠程調用環境,而這恰恰是單元測試所忌的。PowerMockito提供了對靜態方法模擬的支持,網上已有大量關於JUnit+PowerMockito的整合示例,但是關於TestNG+PowerMockito比較少,本文記錄實際開發中使用TestNG+PowerMockito經驗,以供參考。

 

首先准備一個含有靜態方法的測試類Example:

public class Example {

    public static String get(){
        return "hello";    
    }
            
}

編寫單元測試模擬靜態方法get:

import org.mockito.MockitoAnnotations;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.testng.PowerMockObjectFactory;
import org.testng.IObjectFactory;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.ObjectFactory;
import org.testng.annotations.Test;
import org.testng.Assert;

@PrepareForTest(Example.class)
public class ExampleTest{
    @BeforeClass
    public void before() {
        MockitoAnnotations.initMocks(this);
    }

    @ObjectFactory
    public IObjectFactory getObjectFactory() {
        return new PowerMockObjectFactory();
    }

    @Test
    public void testGet() {
        PowerMockito.mockStatic(Example.class);
        PowerMockito.when(Example.get()).thenReturn("world");
        Assert.assertEquals(Example.get(), "world")
    }    
}    


免責聲明!

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



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