PowerMock的mockStatic()会覆盖X.class.y()方法

时间:2012-08-10 15:29:37

标签: java static powermock java.lang.class

MyClass.java:

package test;
public final class MyClass {
    public MyClass() { }
    public Package returnPackage() {
        return MyClass.class.getPackage();
    }
}

TestClass.java:

package test;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import static org.powermock.api.mockito.PowerMockito.*;

@RunWith(PowerMockRunner.class)
@PrepareForTest(MyClass.class)
public class TestClass {
    @Test
    public void test() throws Exception {
        System.out.println(new MyClass().returnPackage());
        mockStatic(MyClass.class);
        System.out.println(new MyClass().returnPackage());
    }
}

然而,这导致:

package test
null

任何MyClass.class方法调用都会在null之后返回PowerMockito.mockStatic(Class)。有什么方法可以阻止这种情况吗?

1 个答案:

答案 0 :(得分:0)

解决方法:我可以使用EasyMock-API设置不带PowerMockito.mockStatic()的静态模拟。