java - 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。)
解决方案
以下适用于我的 Windows 机器,而您的示例也按预期失败:
try {
Path target = Paths.get(Thread.currentThread().getContextClassLoader()
.getResource(FILE).toURI());
System.out.println(target);
} catch (URISyntaxException e) {
e.printStackTrace();
}
我认为这是因为解析 URI 与解析字符串有不同的实现。
推荐阅读
- sql - pandas.to_sql 函数未按预期转换 dtype
- reactjs - 在本机反应中制作个人资料
- python - 错误输出和无频率的时间序列重采样
- java - Beanshell 是否支持 java 8 流?
- php - Laravel 投票包
- makefile - 在 make 中设置一个 shell 变量,以便稍后在同一行使用
- reactjs - TypeError:getCurves 不是函数
- vue.js - Vue Bootstrap字符串逗号与文本区域分隔的数组?
- sql - SQL:根据 3 个不同的变量选择 MAX 值(按功能分组)
- android - 如何在我的调试器中展开数组的所有子元素?