如何使用在单元测试环境中引发异常的PowerMock模拟Java静态类初始化器

如何使用在单元测试环境中引发异常的PowerMock模拟Java静态类初始化器,java,junit,static-methods,powermock,easymock,Java,Junit,Static Methods,Powermock,Easymock,我正在为现有的遗留代码库编写一个单元测试。它包含一些我想模拟的类,这些类在类级别具有静态初始值设定项 当我尝试模拟该类时,它将失败,在模拟创建期间,静态初始化中的代码出现异常,该异常在JUnit测试环境中不起作用(取决于某些应用服务器) 这是我的情景的简单说明 要模拟的类: public class StaticClass { static { doSomething(); } private static void doSomething() {

我正在为现有的遗留代码库编写一个单元测试。它包含一些我想模拟的类,这些类在类级别具有静态初始值设定项

当我尝试模拟该类时,它将失败,在模拟创建期间,静态初始化中的代码出现异常,该异常在JUnit测试环境中不起作用(取决于某些应用服务器)

这是我的情景的简单说明

要模拟的类:

public class StaticClass {

    static {
        doSomething();
    }

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

    public StaticClass(){
    }
}
单元测试框架在Java7上利用PowerMock/EasyMock/JUnit4

这就是我在单元测试中要做的

@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());
    }
}
这会在以下行抛出java.lang.ExceptionInInitializeError异常:PowerMock.mockStatic(StaticClass.class)


除了在我的示例中重构StaticClass之外,还有没有其他方法可以使用PowerMock来模拟静态初始值设定项,或者从它调用的方法不做任何事情?

多亏了这个问题,我找到了解决方案

使用PowerMock@SuppressStaticInitializationFor注释。请参见此处的文档

此测试代码现在可以工作:

@RunWith(PowerMockRunner.class)
@SuppressStaticInitializationFor("com.my.test.StaticClass")
public class SampleTest {


    @Test
    public void test() {
        StaticClass mockInstance = EasyMock.createNiceMock(StaticClass.class);
        EasyMock.replay(mockInstance);

        System.out.println(mockInstance.toString());
    }

}

多亏了这个问题,我找到了解决办法

使用PowerMock@SuppressStaticInitializationFor注释。请参见此处的文档

此测试代码现在可以工作:

@RunWith(PowerMockRunner.class)
@SuppressStaticInitializationFor("com.my.test.StaticClass")
public class SampleTest {


    @Test
    public void test() {
        StaticClass mockInstance = EasyMock.createNiceMock(StaticClass.class);
        EasyMock.replay(mockInstance);

        System.out.println(mockInstance.toString());
    }

}