gpt4 book ai didi

java - PowerMockito 无法模拟 FileInputStream 的构造函数

转载 作者:行者123 更新时间:2023-11-29 03:33:46 25 4
gpt4 key购买 nike

我正在尝试模拟 FileInputStream 的构造函数,我有以下代码:

@RunWith(PowerMockRunner.class)
@PrepareForTest(FileInputStream.class)
public class DBUtilsTest {

@Test(expected = FileNotFoundException.class)
public void readTableMetadataFileNotFoundException() throws Exception {
try {
PowerMockito.whenNew(FileInputStream.class)
.withParameterTypes(String.class)
.withArguments(Matchers.any(String.class))
.thenThrow(FileNotFoundException.class);

PowerMock.replayAll();

TableMetadata tableMeta = DBUtils
.readTableMetadata(path);
} finally {
PowerMock.verifyAll();
}
}
}
public class DBUtils {
public static TableMetadata readTableMetadata(String metadataPath)
throws FileNotFoundException, IOException {

Properties properties = new Properties();
FileInputStream is = new FileInputStream(metadataPath);
properties.load(is);
.....
}
}

不过,测试失败并显示 java.lang.AssertionError: Expected exception: java.io.FileNotFoundException

似乎构造函数并没有真正被模拟,也没有抛出异常。任何人都可以帮助解决这个问题吗?

最佳答案

我发现我应该准备测试被测类,即 DBUtils,而不是 FileInputStream 类。

@PrepareForTest(DBUtils.class)

可以找到一些有用的例子here .

关于java - PowerMockito 无法模拟 FileInputStream 的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16597676/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com