PowerMock is provided with the annotation @SuppressStaticInitializationFor
to disable the static initializer.
When the class is loaded, the static initializer sets the field to the string "value".
Here, we have prepared a judge method that returns true if the field is set to "value" and false otherwise.
SampleEm.java
public class SampleEm {
private static String field = null;
static {
field = "value";
}
public boolean judge() {
return "value".equals(field);
}
}
To use PowerMock with JUnit, specify PowerMockRunner for @RunWith
.
For @PrepareForTest
, specify the class to mock.
I also specify a class to mock in @SuppressStaticInitializationFor
, but be aware that it is not@SuppressStaticInitializationFor (SampleEm.class)
.
@RunWith(PowerMockRunner.class)
@PrepareForTest(SampleEm.class)
@SuppressStaticInitializationFor("jp.co.sample_powermock.staticinitializer.SampleEm")
public class SampleEmTest {
@Test
public void test() throws Exception {
//Run
SampleEm em = new SampleEm();
boolean result = em.judge();
//Check the result
assertFalse(result);
}
}
When I run the test, this JUnit succeeds because the static initializer is disabled and the field is not set to "value".