I am writing a unit test for an existing legacy code base. It contains some classes that I would like to mock, which have static initializer at the class level.
When I try to mock the class it will fail, during the mock creation with an exception from code within the static initialization that does not work in the JUnit test environment (depends on certain app server).
this is a simple illustration of my scenario
Class to mock:
public class StaticClass {
static {
doSomething();
}
private static void doSomething() {
throw new RuntimeException("Doesn't work in JUnit test environment");
}
public StaticClass(){
}
}
The Unit test framework is leveraging PowerMock/EasyMock/JUnit 4 on Java 7.
This is what I was trying to do in my unit test
@RunWith(PowerMockRunner.class)
@PrepareForTest({StaticClass.class})
public class SampleTest {
@Test
public void test() {
PowerMock.mockStatic(StaticClass.class);
PowerMock.replay(StaticClass.class);
StaticClass mockInstance = EasyMock.createNiceMock(StaticClass.class);
EasyMock.replay(mockInstance);
System.out.println(mockInstance.toString());
}
}
This throws the java.lang.ExceptionInInitializerError exception at the line: PowerMock.mockStatic(StaticClass.class);
Other than refactoring the StaticClass in my example, is there any other way to use PowerMock to mock the static initializer, or methods called from it to do nothing?