jUnit模拟测试并覆盖IOException

时间:2019-03-24 08:50:31

标签: java spring spring-boot junit mockito

我有以下代码段:

try {
        Properties properties = new Properties();
        properties.load(Thread.currentThread().getContextClassLoader()
            .getResourceAsStream("application.properties"));
        String accessKey = properties.getProperty("");
        String secretKey = properties.getProperty("");
        return new BasicAWSCredentials(accessKey, secretKey);
    } catch (FileNotFoundException io) {
        log.error("Properties file not found.");
        return null;
    } catch (IOException io) {
        log.error("Error loading property.");
        return null;
    } catch (IllegalArgumentException io) {
        log.error("Access Key or Secret key not present/found");
        return null;
    }

在jUnit中,我能够测试并涵盖FileNotFoundExceptionIllegalArgumentException是否成功,但是在这种情况下,我无法涵盖并测试IOException。我是编写测试的新手。我还尝试了理解Mockito,但是找不到解决这种情况的方法。

1 个答案:

答案 0 :(得分:0)

您可以尝试使用PowerMockito.mockNew(https://automationrhapsody.com/mock-new-object-creation-powermock/)模拟创建新的Properties对象。然后您可以模拟一个例外情况