java - 如何在单元测试环境中使用抛出异常的 PowerMock 来模拟 Java 静态类初始化器

标签 java junit static-methods powermock easymock

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

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

这是我的场景的简单说明

要模拟的类:

public class StaticClass {

    static {
        doSomething();
    }

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

    public StaticClass(){
    }
}

单元测试框架在 Java 7 上利用 PowerMock/EasyMock/JUnit 4。

这就是我在单元测试中尝试做的事情

@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.ExceptionInInitializerError 异常:PowerMock.mockStatic(StaticClass.class);

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

最佳答案

由于问题Why PowerMock is attempting to load the server.xml file if the static class is mocked out?,我找到了解决方案

使用 PowerMock @SuppressStaticInitializationFor 注释。请在此处查看他们的文档 PowerMock wiki - Suppress Unwanted Behavior

此测试代码现在可以运行:

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

}

关于java - 如何在单元测试环境中使用抛出异常的 PowerMock 来模拟 Java 静态类初始化器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39796908/

相关文章:

java - JMockit withCapture 不工作

c# - 为什么静态构造函数没有任何参数?

c# - 是否可以在 C# 中使用全局方法

c++ - 总是在 C++ 中创建类?

java - Jsoup - 为 POST 传递原始正文

java - 包含 Spring 的 @Transactional 注解的方法的方法转发?

java - 来自 Gradle 的 Android 中的 JUnit 测试 : "package android.test does not exist"

java - 是否有与 NUnit 的 TestCaseAttribute 等效的 JUnit?

java - 有没有更好的方法来处理国家及其州/省/地区列表?

java - 拖放监听器和处理程序不起作用 [JavaFX]