'Mock and throw error for File readAllBytes

Want to mock File.readAllBytes to throw error first and then bytes[]..

getQueryTextFromFile is a private method and calling from another method to get bytes[]

private byte[] getQueryTextFromFile() {
        try {
            File file = new File("./");
            byte[] refreshTableQueryBytes = Files
                    .readAllBytes(Paths.get(file.getAbsolutePath() +"src/resources/queryFile"));
            return refreshTableQueryBytes;
        } catch (IOException e) {
            logger.error("Exception while fetching query details");
        }
        return null;
    }

How to mock here to throw IOException using Mockito Framework



Solution 1:[1]

You can mock Files by Mockito.mockStatic. You should add mockito-inline dependency to your pom.xml:

<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-inline</artifactId>
    <version>3.8.0</version>
    <scope>test</scope>
</dependency>

You can use Mockito.mockStatic in this way:

try (MockedStatic<Files> mockedFiles = Mockito.mockStatic(Files.class)) {
    mockedFiles.when(() -> Files.readAllBytes(any())).thenThrow(IOException.class);
    // ...
}

Note that, when you use mockedStatic, you had better use try-with-resources pattern and do your test in this scope like above.

Read more about mockStatic: https://www.baeldung.com/mockito-mock-static-methods

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kai-Sheng Yang