2014-09-21 18 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中鎖定目標。你應該考慮重構測試。