在编写单元测试的时候,常常需要模拟静态方法。例如一个测试方法依赖于一个执行远程调用的静态方法,如果不模拟静态方法,就可能需要准备远程调用环境,而这恰恰是单元测试所忌的。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") } }