PowerMockito无法模拟FileInputStream的构造函数

时间:2013-05-16 21:19:33

标签: 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);
        .....
    }
}

但是,测试失败了java.lang.AssertionError: Expected exception: java.io.FileNotFoundException

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

1 个答案:

答案 0 :(得分:3)

我发现我应该准备测试测试类,这意味着DBUtils,而不是FileInputStream类。

@PrepareForTest(DBUtils.class)

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