Mock and throw error for File readAllBytes

Viewed 227

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

1 Answers

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

Related