PowerMockito 无法模拟 FileInputStream 的构造函数

Ali*_*ila 1 java junit mocking powermock

我正在尝试模拟 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);
        .....
    }
}
Run Code Online (Sandbox Code Playgroud)

虽然,测试失败 java.lang.AssertionError: Expected exception: java.io.FileNotFoundException

似乎构造函数并没有真正被嘲笑,也没有抛出异常。任何人都可以对这个问题提供任何帮助吗?

Ali*_*ila 5

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

@PrepareForTest(DBUtils.class)
Run Code Online (Sandbox Code Playgroud)

一些有用的例子可以在这里找到。