I'm trying to test the following class which calls out to a singleton that initializes a private static final variable by mocking it out, following this example.
Here's what I'm doing
public class ClassToTest {
private static final boolean CONF_FLAG = Configuration.getConfig()
.get(Status.Initialization).getConfFlag(); // throws an NPE
public methodToTest(TestObject a){
...
}
}
where Status is an Enum.
Test class :
public class TestClassToTest{
TestObject a;
ClassToTest t;
@Before
public void setUp() throws Exception {
setFinalStatic(ClassToTest.class.getDeclaredField("CONF_FLAG"), true);// this fails!
a = mock(TestObject.class);
t = new ClassToTest();
}
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);
}
}
I don't care for the value of CONF_FLAG
but cant seem to mock it out. What am I doing wrong?