简体   繁体   中英

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) (eg only classes with builders matching **/*Builder.* pattern) as a testCompile dependency in another subproject?

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 (eg 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 (eg project(':subFoo1').sourceSets.test.output ) is problematic, and should be avoided when possible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM