2014-09-21 96 views
0

当使用powermock抑制类的构造函数时,如何设置私有final字段的值?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(); 
    } 
} 

回答

2

像往常一样,通过使用反射:

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

这是不相关的嘲讽因此嘲笑框架不会在其API中锁定目标。你应该考虑重构测试。