繁体   English   中英

Java 中是否有一个友好的文件管理库?

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

我已经使用这个库来处理文件,但现在我想编写简单的单元测试。

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

现在的代码示例代码:

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

所以我需要的是一个与 "Files" 一样的类,但可以注入

底层java.nio.Filesystem允许通过实现自定义java.nio.FilesystemProvider来使用替代文件系统

Google 的JimFS是 InMemory 文件系统的这种实现,只要您远离java.io.File类(不受支持),它就可以很好地用于测试目的

另一个选择是使用在本地文件系统上运行的测试工具,例如 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);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM