首页 > 解决方案 > Java单元测试中Windows上的测试资源路径

问题描述

我正在使用此代码Path在测试代码中获取测试资源文件:

Path target = Path.of(
    Thread.currentThread().getContextClassLoader()
      .getResource("target1").getFile()
);

该文件位于src/test/resources/target1并在构建时复制到target/test-classes/tartget1.

它在类 Unix 系统上运行良好,但在 Windows 上会引发异常:

java.nio.file.InvalidPathException: Illegal char <:> at index 2: /D:/a/project-name/repo-name/target/test-classes/target1

使用堆栈跟踪(来自 CI 机器):

在 java.base/sun.nio.fs.WindowsPathParser.normalize(WindowsPathParser.java:182)
在 java.base/sun.nio.fs.WindowsPathParser.parse(WindowsPathParser.java:153)
在 java.base/sun.nio .fs.WindowsPathParser.parse(WindowsPathParser.java:77)
在 java.base/sun.nio.fs.WindowsPath.parse(WindowsPath.java:92)
在 java.base/sun.nio.fs.WindowsFileSystem.getPath(WindowsFileSystem .java:229)
在 java.base/java.nio.file.Path.of(Path.java:147)

Path获得与平台无关的方式的正确方法是什么?我想对 Unix 和 Windows 机器使用相同的代码。(对我来说很难调试这个问题,因为我没有 Windows 机器只有 CI 和 Windows。)

标签: javawindowsjunit

解决方案


以下适用于我的 Windows 机器,而您的示例也按预期失败:

try {
  Path target = Paths.get(Thread.currentThread().getContextClassLoader()
      .getResource(FILE).toURI());
  System.out.println(target);
} catch (URISyntaxException e) {
  e.printStackTrace();
}

我认为这是因为解析 URI 与解析字符串有不同的实现。


推荐阅读