【问题标题】:PowerMock's mockStatic() overwrites X.class.y() methodsPowerMock 的 mockStatic() 覆盖 X.class.y() 方法
【发布时间】:2012-08-10 15:29:37
【问题描述】:

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 方法调用在PowerMockito.mockStatic(Class) 之后返回null。有什么办法可以预防吗?

【问题讨论】:

  • 你想在这里做什么。
  • @GarrettHall 我试图模拟一个构造函数
  • 我还是不明白你到底想做什么。你想模拟一个 MyClass 实例而你不能因为它是 final 的吗?

标签: java static powermock java.lang.class


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-30
    • 2014-06-15
    • 2012-03-23
    • 2017-01-03
    • 1970-01-01
    • 1970-01-01
    • 2018-02-08
    • 1970-01-01
    相关资源
    最近更新 更多