简体   繁体   English

如何使用来自其他子项目的选定类作为 Gradle 中的测试依赖项

[英]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.例如,我只想使用测试数据构建器,在这种情况下,像 test-logback.xml(和常规测试)这样的文件会污染主模块中的测试类路径。

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.我尝试使用 test JAR(它可以过滤内容,但作为依赖项有问题)和eachFileRecurse一些组合,但没有运气。

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?如何仅添加给定源集的一个子集(例如,仅具有匹配**/*Builder.*模式的**/*Builder.*类)作为另一个子项目中的 testCompile 依赖项?

You'll want something along the lines of:你会想要一些类似的东西:

upstream/build.gradle : 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 : 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.除了使用testRuntime ,您还可以声明(例如configurations { testFixture } )并使用自定义配置,这将使您更好地控制将哪些外部依赖项传递给下游项目。 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. PS:接触到另一个项目的对象模型(例如project(':subFoo1').sourceSets.test.output )是有问题的,应该尽可能避免。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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