0
点赞
收藏
分享

微信扫一扫

PowerMockito模拟private static final类变量

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";

ReflectionTestUtils.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);
    }
}

 



举报

相关推荐

0 条评论