Search code examples
pathmockitopowermockitofileutils

Files/Paths/FileUtils - Mock several static classes in one test


I have to mock the below method:

public static void cleanAndCreateDirectories(@NonNull final Path path) throws IOException {
        // If download directory exists(should not be symlinks, clear the contents.
        System.out.println(path);
        if (Files.exists(path, LinkOption.NOFOLLOW_LINKS)) {
            System.out.println("lol");
            FileUtils.cleanDirectory(path.toFile());
        } else {
            // Eager recursive directory creation. If already exists then doesn't do anything.
            Files.createDirectories(path);
        }
    }

I have tried doing like this but it doesn't work:

@Test
public void cleanAndCreateDirectoriesPathExistsHappyCase() throws IOException {
    PowerMockito.mockStatic(Paths.class);
    PowerMockito.when(Paths.get("/dir/file")).thenReturn(FileSystems.getDefault().getPath("/dir/file"));
    PowerMockito.mockStatic(Files.class);
    PowerMockito.when(Files.exists(Paths.get("/dir/file"), LinkOption.NOFOLLOW_LINKS)).thenReturn(true);
    File file = new File("/dir/file");
    Mockito.when(Paths.get("/dir/file").toFile()).thenReturn(file);
    PowerMockito.mockStatic(FileUtils.class);
    ArsDumpGeneratorUtil.cleanAndCreateDirectories(Paths.get("/dir/file"));
}

I am getting following exception message:

File cannot be returned by get()
    [junit] get() should return Path

Am I doing something wrong? Please tell me the best practice for this.


Solution

  • Solved as follows:

    @Test
    public void cleanAndCreateDirectoriesPathExistsHappyCase() throws IOException {
        PowerMockito.mockStatic(Files.class);
        PowerMockito.when(Files.exists(Paths.get("/dir/Exist"), LinkOption.NOFOLLOW_LINKS)).thenReturn(true);
        // Mock FileUtils.
        PowerMockito.mockStatic(FileUtils.class);
        PowerMockito.doNothing().when(FileUtils.class);
        // Call internal-static method.
        FileUtils.cleanDirectory(Matchers.any());
        // Call target method.
        ArsDumpGeneratorUtil.cleanAndCreateDirectories(Paths.get("/dir/Exist"));
        // Check internal-static method call.
        PowerMockito.verifyStatic(Mockito.times(1));
        FileUtils.cleanDirectory(Matchers.any());
    }
    
    @Test
    public void cleanAndCreateDirectoriesPathNotExistsHappyCase() throws IOException {
        PowerMockito.mockStatic(Files.class);
        PowerMockito.when(Files.exists(Paths.get("/dir/NotExist"), LinkOption.NOFOLLOW_LINKS)).thenReturn(false);
        PowerMockito.when(Files.createDirectories(Paths.get("/dir/NotExist"))).thenReturn(Paths.get("/dir/NotExist"));
        // Call target method.
        ArsDumpGeneratorUtil.cleanAndCreateDirectories(Paths.get("/dir/NotExist"));
        // Check internal-static method call.
        PowerMockito.verifyStatic(Mockito.times(1));
        Files.createDirectories(Matchers.any());
    }