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); } }
原文地址:https://www.cnblogs.com/nizuimeiabc1/p/12173907.html
时间: 2024-10-12 11:43:33