java - 我可以在单元测试时模拟特定的文件系统吗?

标签 java junit junit4 java-6

我在谷歌上搜索了一下,没有找到适合我的具体情况的答案。

我正在研究一个项目文件管理器类,发现它被开发为在 Windows 和 Unix 文件系统上表现不同。

更具体地说,它是对 Unix 中区分大小写的补偿:当找不到文件时,管理器将以不区分大小写的方式查找它。

在更改这段代码之前,我想实现一些单元测试。但是,我们的开发机器和我们的 CIP 都在 Windows 上,我没有可用的 Unix 机器。机器和 IDE 由客户提供。虚拟化不是一个选项,双启动更不是。

有没有一种方法可以同时测试 Windows 和 Unix 模式,同时让构建独立于平台?我认为理想的做法是在一种模式下运行整个测试类,然后在另一种模式下运行,但即使是更实用的解决方案也会很棒。

在生产模式下,文件管理器使用 Spring 初始化,但它们是链的最低级别,直接使用 java.io。

版本:Java 6、JUnit 4.9

最佳答案

您可以使用 Jimfs有依赖性

<dependency>
    <groupId>com.google.jimfs</groupId>
    <artifactId>jimfs</artifactId>
    <version>1.1</version>
</dependency>

然后你可以创建一个 linux,windows 和 Mac 文件系统使用

 FileSystem fileSystem = Jimfs.newFileSystem(Configuration.osX());
 FileSystem fileSystem = Jimfs.newFileSystem(Configuration.windows());
 FileSystem fileSystem = Jimfs.newFileSystem(Configuration.unix());

例子

class FilePathReader {

    String getSystemPath(Path path) {
        try {
            return path
              .toRealPath()
              .toString();
        } catch (IOException ex) {
            throw new UncheckedIOException(ex);
        }
    }
}

class FilePathReaderUnitTest {

    private static String DIRECTORY_NAME = "baeldung";

    private FilePathReader filePathReader = new FilePathReader();

    @Test
    @DisplayName("Should get path on windows")
    void givenWindowsSystem_shouldGetPath_thenReturnWindowsPath() throws Exception {
        FileSystem fileSystem = Jimfs.newFileSystem(Configuration.windows());
        Path path = getPathToFile(fileSystem);

        String stringPath = filePathReader.getSystemPath(path);

        assertEquals("C:\\work\\" + DIRECTORY_NAME, stringPath);
    }

    @Test
    @DisplayName("Should get path on unix")
    void givenUnixSystem_shouldGetPath_thenReturnUnixPath() throws Exception {
        FileSystem fileSystem = Jimfs.newFileSystem(Configuration.unix());
        Path path = getPathToFile(fileSystem);

        String stringPath = filePathReader.getSystemPath(path);

        assertEquals("/work/" + DIRECTORY_NAME, stringPath);
    }

    private Path getPathToFile(FileSystem fileSystem) throws Exception {
        Path path = fileSystem.getPath(DIRECTORY_NAME);
        Files.createDirectory(path);

        return path;
    }
}

所有这些复制自 Baeldung .

关于java - 我可以在单元测试时模拟特定的文件系统吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17464669/

相关文章:

java - JUnitParamsRunner 与输入文件 - 字符串参数问题

java - 如何用不同的单元测试方法加载不同的资源?

java - Maven 找不到 org.junit,即使它在依赖项中

java - 使用另一个 Suite 类启动 Suite 类

java - 使用 For 创建 JToggleButtons

Java Swing 程序结构

java - 为 @ExceptionHandler 编写 JUnit 测试

mysql - 如何使用 Spring boot 从 select 查询中获取结果

java - 如何将 Jackson mixin 添加到读取器而不是对象映射器?

Jenkins 的 Java API