Michael Ekstrand Michael Ekstrand - 2 months ago 12
Java Question

How can I have a Maven dependency on the runtime classpath but not the test classpath?

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?

Answer

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:

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-surefire-plugin</artifactId>
  <version>2.8</version>
  <configuration>
    <classpathDependencyExcludes>
      <classpathDependencyExclude>ch.qos.logback:logback-classic</classpathDependencyExclude>
    </classpathDependencyExcludes>
  </configuration>
</plugin>