使用PowerMock来Mock静态函数
EasyMock和Mockito等框架,对static, final, private方法均是不能mock的。 这些框架普遍是通过创建Proxy的方式来实现的mock。 而PowerMock是使用CGLib来操纵字节码而实现的mock,所以它能实现对上面方法的mock。今天先来看一个简单的例子吧:
第一个注解是指定Runner
第二个是你要测试的类,这个里面调用了静态类
下面我结合EasyMock给一个简单的例子:
import java.io.IOException;public class SystemPropertyMockDemo {public String getSystemProperty() throws IOException {return System.getProperty("property");}}import org.easymock.EasyMock;import org.junit.Assert;import org.junit.Test;import org.junit.runner.RunWith;import org.powermock.api.easymock.PowerMock;import org.powermock.core.classloader.annotations.PrepareForTest;import org.powermock.modules.junit4.PowerMockRunner;@RunWith(PowerMockRunner.class)@PrepareForTest({SystemPropertyMockDemo.class})public class SystemPropertyMockDemoTest {@Testpublic void demoOfFinalSystemClassMocking() throws Exception {PowerMock.mockStatic(System.class); EasyMock.expect(System.getProperty("property")).andReturn("my property"); PowerMock.replayAll(); Assert.assertEquals("my property", new SystemPropertyMockDemo().getSystemProperty()); PowerMock.verifyAll();}}<dependency> <groupId>org.powermock</groupId> <artifactId>powermock-module-junit4</artifactId> <version>1.4.8</version> <scope>test</scope> </dependency> <dependency> <groupId>org.powermock</groupId> <artifactId>powermock-api-easymock</artifactId> <version>1.4.8</version> <scope>test</scope> </dependency>