PowerMockito.mockStatic時忽略加載類的靜態field,比如想PowerMockito.mockStatic(ClassA.class),ClassA如下
public class ClassA { private static final boolean CONF_FLAG = Configuration.getConfig() .get(Status.Initialization).getConfFlag(); // throws an NPE public static methodTobeCalledByOtherTestMethod(TestObject a){ ... } }
filed CONF_FLAG需要調用一些其他依賴,而這些依賴不可獲得,當mock時會拋異常,可以使用:
@RunWith(PowerMockRunner.class) @PrepareForTest({ClassA.class}) @SuppressStaticInitializationFor("com.xxx.xxx.ClassA") public class XXXTest { @Test public void testXXX() { PowerMockito.mockStatic(ClassA.class); .... } }
使用SuppressStaticInitializationFor就不會去初始化CONF_FLAG。
另外其他忽略的配置請見:Suppress Unwanted Behavior
參考:What am I doing wrong mocking this private static final variable using mockito and reflection?
修改某個靜態函數的返回值:PowerMock, mock a static method, THEN call real methods on all other statics