如何使 Maven 依赖于运行时类路径而不依赖于测试类路径?
我有一个情况,我想要依赖于运行时类路径,但不测试类路径。有问题的依赖项是 Logback,一个 SLF4J 实现。在运行时,我希望我的代码(可选)依赖于 logback,以便它具有可用的日志记录基础设施。然而,在测试时,我想使用 slf4j-nop 实现来黑洞日志输出。使用 logback 作为运行时依赖项和 slf4j-nop 作为测试依赖项,我在运行测试时收到来自 SLF4J 的多重实现警告。我没有找到从测试类路径中排除 logback
的方法。
如果可以避免的话,我不想将我的测试分成一个单独的包。
有想法吗?
I have a case where I want a dependency on the runtime classpath but not the test classpath. The dependency in question is Logback, an SLF4J implementation. In runtime, I want my code to (optionally) depend on logback so that it has a logging infrastructure available. At test time, however, I want to use the slf4j-nop
implementation to black-hole the log output. With logback
as a runtime dependency and slf4j-nop
as a test dependency, I get a multiple implementation warning from SLF4J when running my tests. I do not see a way to exclude logback
from the test classpath.
I do not want to split my tests into a separate package if it can be avoided.
Ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我终于找到了真正的解决方案。从 Maven Surefire 插件 2.6 版本开始,现在有一个 classpathDependencyExcludes 配置元素,允许从类路径中排除特定的依赖项。因此,这有效:
I've finally found a real solution to this. Since version 2.6 of the Maven Surefire plugin, there is now a classpathDependencyExcludes configuration element that allows specific dependencies to be excluded from the classpath. This therefore works:
如果您想要禁用日志输出,请将 logback 配置文件添加到 src/test/resources 中,该文件将丢弃所有输出。
如果您需要对同一反应器构建中的多个模块执行此操作,请考虑使用 maven远程资源插件。
If disabling log output is what you want, add a logback configuration file to
src/test/resources
which discards all output.If you need to do this for multiple modules in the same reactor build, consider using the maven remote resources plugin.
据我所知,您不必将其从测试类路径中排除。 Maven 应该保持类路径中依赖项的顺序。如果将测试依赖项放在依赖项中的运行时依赖项之前,它也应该位于类路径的第一个位置,并且当两个依赖项包含相同的类时,类加载器应该首先找到测试依赖项中的类。因此 slf4j 将找到 slf4j-nop 的静态绑定,而不是 logback 绑定。
As far as i know you don't have to exclude it from the test classpath. Maven should keep the order of dependencies in the classpath. If you put your test dependency before the runtime dependency in the dependencies it should also be first in the classpath and a ClassLoader should find the classes in the test dependency first when 2 dependencies contain the same classes. So slf4j would then find the static binding of slf4j-nop and not the logback binding.
从 slf4j-nop 测试范围的依赖项中添加对 logback 的依赖项排除是否有效?像这样的东西
Would it work to add a dependency exclusion on logback from the slf4j-nop test-scoped dependency? Something like