我正在为现有的遗留代码库编写单元测试。它包含一些我想模拟的类,这些类在类级别具有静态初始化程序。
当我尝试模拟该类时,它会失败,在模拟创建期间,静态初始化中的代码出现异常,该异常在 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/