How to mock Java static class initializater Using PowerMock that throws an Exception in a unit test environment
<p>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.</p>

<p>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).</p>

<p>this is a simple illustration of my scenario</p>

<p>Class to mock:</p>

<pre><code>public class StaticClass {

    static {
        doSomething();
    }

    private static void doSomething() {
        throw new RuntimeException("Doesn't work in JUnit test environment");
    }

    public StaticClass(){
    }
}
</code></pre>

<p>The Unit test framework is leveraging PowerMock/EasyMock/JUnit 4 on Java 7.</p>

<p>This is what I was trying to do in my unit test</p>

<pre><code>@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());
    }
}
</code></pre>

<p>This throws the java.lang.ExceptionInInitializerError exception at the line: PowerMock.mockStatic(StaticClass.class);</p>

<p>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?</p>