我正在尝试使用PowerMock和Mockito在类上模拟静态方法,但是有关在该类中使用文件InputStream的某种方法(看似无关的方法)会抛出MockitoException
。
我想模拟CustomProperties.getProperty()
的返回值,但是当我运行测试时,我得到一个MockitoException
,说它不能模拟该类。我已尝试在测试中禁止使用静态初始化器和loadProperties
方法,并且日志语句显示它们已被禁止。问题出在loadProperties
方法内的try / catch周围。一旦我用文件输入流注释掉try / catch,测试就通过了。有人可以解释这个谜吗?
这是课程(为简洁起见进行编辑):
public class CustomProperties {
private static Properties properties = null;
// mock this method's return value
public static String getProperty(String key) {
return properties.getProperty(key);
}
public static synchronized void loadProperties() {
properties = new Properties();
String path = System.getProperty("domain.path");
try (InputStream fileInputStream = Files.newInputStream(Paths.get(path + "/custom.properties"))) {
// do stuff
} catch (IOException e) {
e.printStackTrace();
}
}
static {
loadProperties();
}
}
这是我的考试:
@RunWith(PowerMockRunner.class)
@SuppressStaticInitializationFor("com.company.util.CustomProperties")
@PrepareForTest(CustomProperties.class)
public class SanityTest {
@Before
public void setUp() throws Exception {
mockStatic(CustomProperties.class);
when(CustomProperties.getProperty("someKey")).thenReturn("some value");
suppress(method(CustomProperties.class, "loadProperties"));
}
@Test
public void sanityTest() {
assertEquals("some value", CustomProperties.getProperty("someKey"));
}
}
这是异常堆栈跟踪(为简洁起见进行了编辑):
org.mockito.exceptions.base.MockitoException:
Mockito cannot mock this class: class com.company.util.CustomProperties.
Mockito can only mock non-private & non-final classes.
If you're not sure why you're getting this error, please report to the mailing list.
Java : 1.7
JVM version : 1.7.0_10-b18
Underlying exception : java.lang.IllegalArgumentException: Could not create type
...
Caused by: java.lang.IllegalArgumentException: Could not create type
...
Caused by: java.lang.VerifyError: Inconsistent stackmap frames at branch target 2947 in method com.company.util.CustomProperties.loadProperties()V at offset 2936
...
最后,相关依赖项的版本:
org.mockito:mockito-core:2.28.2
org.powermock:powermock-module-junit4:2.0.2
org.powermock:powermock-api-mockito2:2.0.2
net.bytebuddy:byte-buddy:1.10.1