java - 如何正确地单元测试 "abstracted"文件处理?

标签 java file unit-testing junit temporary-files

我有一个 API,其中文件放置在某个不同的目录中,文件名由固定的前缀/后缀部分组成。我想抽象出这些部分,以便我的助手类的用户可以专注于需要完成的事情。

示例代码:

static class FileManager {
    Path getFilePath(String arg) {
        return Paths.get("/whatever", "prefix_" + arg + "_postfix");
    }

    void deleteFileIfExists(Path path) {
        if (path.toFile().exists())
            path.toFile().delete();
    }

    public void deleteFileIfExistsUsing(String arg) {
        deleteFileIfExists(getFilePath(arg));
    }
}


@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();

@Test
public void testGetFilePath() {
    assertThat(new FileManager().getFilePath("bar"), is(Paths.get("/whatever/prefix_bar_postfix")));
}

@Test
public void testDelete() throws IOException {
    File subfolder = temporaryFolder.newFolder("whatever");
    File fileToDelete = new File(subfolder, "prefix_bar_postfix");
    fileToDelete.createNewFile();
    assertThat(fileToDelete.exists(), is(true));
    new FileManager().deleteFileIfExists(fileToDelete.toPath());
    assertThat(fileToDelete.exists(), is(false));
}

如您所见,可以完全测试 getFilePath()deleteFileIfExists()。但是是否有一种有意义的方法来测试一个 API deleteFileIfExistsUsing(String)

我看到的唯一选择是:使用另一个类来提供基于路径的调用,然后为 FileManager 提供该类的一个实例……这样就可以了被 mock 。但这感觉有点矫枉过正。

那么:还有其他方法可以从 FileManager 测试公共(public)方法吗?

(旁注:一个目标是单元测试在某种程度上是独立于平台的。例如,以上内容实际上适用于 Linux 和 Windows)

最佳答案

注入(inject) Function<String, Path>进入 FileManager 的构造函数:

static class FileManager {
    private final Function<String, Path> pathFactory;

    FileManager(Function<String, Path> pathFactory) {
        this.pathFactory = pathFactory;
    }

    Path getFilePath(String arg) {
        return pathFactory.apply("/whatever/prefix_" + arg + "_postfix");
    }

    // ...
}

然后你可以注入(inject)Paths::get在生产代码中,比如返回 mock Path 的东西s 在测试中。

关于java - 如何正确地单元测试 "abstracted"文件处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57753105/

相关文章:

java - Jsoup select 没有返回所有节点

Ruby MRI 1.8.7 - 文件写入线程安全

unit-testing - Jasmine 参数化单元测试

java - 什么是 setTimeOut() javascript 到 Android 的等价物?

java - 从 TypeReference<E> 转换为 Class<E> 而无需强制转换 (Java)

android - 创建一个xml文件?

java - intelliJ 如何将 gradle 任务作为测试运行

c# - 是否可以将基于接口(interface)的模拟转换为对象?

java - 重新实例化对象而不丢失先前的对象

file - 如何在 Informix 中打开和读取文件