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