I have a Gradle dependency defined like this:
dependencies {
implementation("com.example:my-library:1.0.0")
}
However, I don't want this library to be included in the test classpath. How can I exclude it from tests while keeping it available for the main code? Thanks!
I have a Gradle dependency defined like this:
dependencies {
implementation("com.example:my-library:1.0.0")
}
However, I don't want this library to be included in the test classpath. How can I exclude it from tests while keeping it available for the main code? Thanks!
Share Improve this question asked Mar 14 at 17:00 kikulikovkikulikov 2,5815 gold badges33 silver badges45 bronze badges1 Answer
Reset to default 1Simply excluding a dependency from the test classpath does not appear to be possible. This is for two reasons:
- The test classpaths inherits from the main classpaths, so each main dependency will be there by default; and
- In Gradle non-transitive dependencies are not optional so it's only possible to substitute the unwanted dependency for another, instead of outright rejecting it.
To do this then I suggest doing a "substitution" for a module you are happy to have on the classpath, ie:
// and/or use testRuntimeClasspath depending what you want exactly
configurations.testCompileClasspath {
resolutionStrategy {
dependencySubstitution {
substitute(module("com.example:my-library"))
.using(module("com.example:my-safe-library:1.0.0"))
}
}
}
As you'll be aware, you'll get a ClassNotFoundException
if you try and run code from the main source that uses the excluded module and you've excluded the library from the test runtime classpath.
You probably know also this, but for completeness I should probably say that excluding a dependency in this way suggests that there is something in your setup that is not quite as recommended as such a "hack" should not be necessary; however I appreciate that sometimes a shortcut is needed to "get things working".