gpt4 book ai didi

scala - 在 sbt 中运行主类或测试时无法获取资源

转载 作者:行者123 更新时间:2023-12-04 15:49:37 25 4
gpt4 key购买 nike

我正在尝试运行一个使用 sbt 中的资源的测试。该测试依赖于通过 ClassLoader.getSystemResourceAsStream(...) 加载资源的实用程序,这意外地导致 null。如果我在 Intellij 中或通过 bazel 运行相同的测试,则测试成功。我还通过创建一个主类来根据 this question 的答案中给出的 ResourceList 示例列出所有资源来执行测试。 ,这证实了该文件和许多其他文件在运行时无法访问。

这些资源不包含在sbt通常使用的resources目录中;它们包含在 lib 目录中的 jar 文件中。 sbt 构建的项目中的源严重依赖于此 jar,并且编译成功,因此问题可能特定于资源。我注意到的一件事是,如果我使用 ClassLoader 对象并调用 getResourceAsStream 而不是使用静态方法 ClassLoader.getSystemResourceAsStream,则可以加载资源.

有谁知道如何解决这个问题(除了从 lib 中的 jar 文件中复制所有资源)?

最佳答案

尝试在 forked JVM 中运行测试:

Test / fork := true

Unmanaged dependencieslib/ 中应该默认在所有类路径中结束,包括 test,而无需执行任何特殊操作:

Dependencies in lib go on all the classpaths (for compile, test, run, and console).

请注意,在 IntelliJ 中运行测试时,您可能会使用 IntelliJ 的内部构建系统而不是 SBT shell,这可能是它在 IntelliJ 中运行的原因。要通过 sbt shell 在 IntelliJ 中运行测试,请选择 Use sbt Edit Configurations...

中的复选框

我建议使用 getClass.getResourceAsStream ,因为这无论如何都使用 system ClassLoader 作为 fallback :

     public InputStream getResourceAsStream(String name) {
name = resolveName(name);
ClassLoader cl = getClassLoader0();
if (cl==null) {
// A system class.
return ClassLoader.getSystemResourceAsStream(name);
}
return cl.getResourceAsStream(name);
}

关于scala - 在 sbt 中运行主类或测试时无法获取资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54411509/

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