在編寫單元測試的時候,常常需要模擬靜態方法。例如一個測試方法依賴於一個執行遠程調用的靜態方法,如果不模擬靜態方法,就可能需要准備遠程調用環境,而這恰恰是單元測試所忌的。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") } }