Java有没有di友好的文件管理库?

Is there a di-friendly File management library in Java?

我曾经 this library 处理文件,但现在我想编写简单的单元测试。

问题:文件 class 是静态最终的,方法是静态的,因此是不可模拟的。 对我来说,这是令人沮丧的,因为我现在需要实际测试文件系统并实际测试结果,而我需要做的只是模拟方法。不是真正的单元测试,当你需要实际使用环境时。

现在代码的示例代码:

public class MyClass
{
    public void myMethod(File myFile) throws IOException
    {
        Files.move(myFile.toPath(), myFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
    }
}

我希望代码是这样的:

public class MyClass
{
    private final Files files;

    public MyClass(Files files)
    {
        this.files = files;
    }

    public void myMethod(File myFile) throws IOException
    {
        this.files.move(myFile.toPath(), myFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
    }
}

所以我需要的是 class 与 "Files" 功能相同,但可注射

标的java.nio.Filesystem allows to use an alternative filesystem by implementing a custom java.nio.FilesystemProvider

Google的JimFS就是这样一个InMemory文件系统的实现,只要你远离java.io.File[=26=,它可以很好地用于测试目的](不支持)

另一种选择是使用在本地文件系统上运行的测试工具,例如 JUnit 4s TemporaryFolder 规则

@Rule
public TemporaryFolder temp = new TemporaryFolder()

您可以在此文件夹中创建文件,测试您的移动操作。该规则确保文件夹在测试完成后关闭。

添加了我的意思的一个小实现。现在它可以很容易地注射。 https://github.com/drakonli/jcomponents/tree/master/src/main/java/drakonli/jcomponents/file/manager

package drakonli.jcomponents.file.manager;

import java.io.IOException;
import java.nio.file.CopyOption;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.FileAttribute;

public class NioFileManager implements IFileManager
{
    @Override
    public Path move(Path source, Path target, CopyOption... options) throws IOException
    {
        return Files.move(source, target, options);
    }

    @Override
    public Path copy(Path source, Path target, CopyOption... options) throws IOException
    {
        return Files.copy(source, target, options);
    }

    @Override
    public boolean isSameFile(Path path, Path path2) throws IOException
    {
        return Files.isSameFile(path, path2);
    }

    @Override
    public Path createTempFile(String prefix, String suffix, FileAttribute<?>... attrs) throws IOException
    {
        return Files.createTempFile(prefix, suffix, attrs);
    }
}