How to use selected classes from other subproject as test dependency in Gradle
gradle, java
Solution
You'll want something along the lines of:
`upstream/build.gradle`:
apply plugin: "java"
task testJar(type: Jar) {
classifier = "tests"
from sourceSets.test.output
exclude "**/*Test.class"
}
artifacts {
testRuntime testJar
}
`downstream/build.gradle`:
apply plugin: "java"
dependencies {
testCompile project(path: ":upstream", configuration: "testRuntime")
}
Instead of using `testRuntime`, you could also declare (e.g. `configurations { testFixture }`) and use a custom configuration, which would give you more control over which external dependencies are passed on to downstream projects. Yet another option would be to declare a separate source set for the part of the test code that is to be passed on. (This would also give you separate compile and runtime configurations to work with.)
PS: Reaching out into another project's object model (e.g. `project(':subFoo1').sourceSets.test.output`) is problematic, and should be avoided when possible.
Problem
To add a simple dependency on test source sets from an another subproject I can do: ``` testCompile project(':subFoo1').sourceSets.test.output ``` This solution works, but in many cases it is not intended to add the whole source set as a dependency. For example I would like to use only test data builders and in that case files like test-logback.xml (and regular tests) pollute my test classpath in the master module. I tried the idea with test JAR (which can have filtered content, but is problematic as a dependency) and some combination with `eachFileRecurse`, but with no luck. My question. How can I add only a subset of given source set(s) (e.g. only classes with builders matching `**/*Builder.*` pattern) as a testCompile dependency in another subproject?