如何在Java中编写单元测试以加载文件

时间:2019-03-19 06:24:40

标签: java unit-testing junit mockito

我想执行单元测试以检查Java中的文件加载。我在 Mockitos doThrow 上看到了一些帖子,但没有确切地实现它。

我的方法看起来像这样。

    public void loadPropertiesFile(String filepath){
    logger.info("Loading properties file");
    try{
        prop.load(new FileInputStream(filepath));
        logger.info("Properties file read");
    }catch(IOException e){
        e.printStackTrace();
        logger.info("Properties file read error");
    }
}

我正在尝试像这样进行测试,但由于doThrow使用不当而出现错误:

@Test
    public void loadPropertiesFileTestTrue(){
        Utility util=new Utility();

        doThrow(FileNotFoundException.class)
            .when(util)
            .loadPropertiesFile(null);

    }

1 个答案:

答案 0 :(得分:1)

您只能在模拟对象上使用doThrow()方法。
您应该这样更改代码:

@Test
public void loadPropertiesFileTestTrue(){
     Utility util=Mockito.mock(Utility.class);

     doThrow(FileNotFoundException.class)
            .when(util)
            .loadPropertiesFile(null);

}