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

时间:2017-02-27 09:53:18

标签: path mockito powermockito fileutils

我必须嘲笑以下方法:

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

我做错了吗?请告诉我最好的做法。

1 个答案:

答案 0 :(得分:0)

解决如下:

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