标签:mil object utils private dem field code The declared
mock模拟private static final now=system.currentmills;
首先在测试类开头加上:
@prepareForTest({System.class})
Class A{
}
然后,在方法上添加:
powermockito.mockstatic(system.class);
powermockito.when(system.currentmills).thenreturn(now);
system.currentmills;
如果要mock模拟类的变量Class A {
private String a;
}
可以这样:
String a = "test";
ReflectionUtils.set(new A(),‘a‘,a);
如果要mock模拟类的变量private static final变量
public class Class1Test { @Test public void test() throws Exception { Logger logger = Mockito.mock(Logger.class); Mockito.when(logger.isInfoEnabled()).thenReturn(false); setFinalStatic(Class1.class.getDeclaredField("LOGGER"), logger); Class1 cls1 = new Class1(); assertFalse(cls1.demoMethod()); } static void setFinalStatic(Field field, Object newValue) throws Exception { field.setAccessible(true); Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); field.set(null, newValue); } }
PowerMockito模拟private static final类变量
标签:mil object utils private dem field code The declared
原文地址:https://www.cnblogs.com/nizuimeiabc1/p/12173907.html