PowerMock - 抑制构造函数但设置私有final字段

时间:2014-09-21 13:15:03

标签: java junit mocking mockito powermock

使用powermock抑制类的构造函数时,如何设置私有final字段的值?

压制构造函数:

suppress(constructor(ABC.class, MyType.class));
ABC abc = spy(new ABC(null)); // using the correct value doesn't work
abc.someMethod();

要测试的课程:

class ABC {
    private final MyType test;

    public ABC(MyType test) {
        this.test = test;

        // executes code to be suppressed
    }

    public void someMethod() {
        test.doSomethingElse();
    }
}

1 个答案:

答案 0 :(得分:2)

正如您通常所做的那样,使用反射:

Field f = ABC.class.getDeclaredField("test");
f.setAccessible(true);
f.set(abc, new MyType());

这与模拟无关,因此其API中没有任何模拟框架。您应该考虑重构以进行测试。

相关问题