Marcin Zajączkowski
Marcin Zajączkowski

Reputation: 4136

How to use selected classes from other subproject as test dependency in Gradle

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?

Upvotes: 3

Views: 2701

Answers (1)

Peter Niederwieser
Peter Niederwieser

Reputation: 123978

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.

Upvotes: 5

Related Questions