Files/Paths/FileUtils - 在一次测试中模拟多个静态 类

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

我必须模拟以下方法:

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);
        }
    }

我试过这样做,但没有用:

@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"));
}

我收到以下异常消息:

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

我是不是做错了什么?请告诉我最佳做法。

解决如下:

@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());
}