gpt4 book ai didi

java - Java 单元测试中 Windows 上的测试资源路径

转载 作者:行者123 更新时间:2023-12-01 13:11:03 24 4
gpt4 key购买 nike

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

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 机器):

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

以与平台无关的方式获取 Path 的正确方法是什么?我想对 Unixes 和 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 与解析字符串的实现不同。

关于java - Java 单元测试中 Windows 上的测试资源路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59897473/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com