简体   繁体   English

PowerMockito无法模拟FileInputStream的构造函数

[英]PowerMockito cannot mock constructor for FileInputStream

I am trying to mock the constructor for the FileInputStream and I have the following code: 我试图模拟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);
        .....
    }
}

Though, the test fails with java.lang.AssertionError: Expected exception: java.io.FileNotFoundException 但是, java.lang.AssertionError: Expected exception: java.io.FileNotFoundException测试失败java.lang.AssertionError: Expected exception: java.io.FileNotFoundException

It seems that the constructor isn't really mocked and the exception does not get thrown. 似乎构造函数并没有真正被模拟,并且异常不会被抛出。 Can anyone give any help with this issue? 任何人都可以帮助解决这个问题吗?

I found out that I should prepare for test the tested class, meaning DBUtils, and not the FileInputStream class. 我发现我应该准备测试测试类,即DBUtils,而不是FileInputStream类。

@PrepareForTest(DBUtils.class)

some useful examples can be found here . 一些有用的例子可以在这里找到。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM