我有两个项目,项目A和项目B。这两个项目都是用groovy编写的,并使用gradle作为其构建系统。
项目A需要项目B。这对于编译和测试代码均适用。
如何配置项目A的测试类可以访问项目B的测试类?
Answers:
您可以通过“ tests”配置公开测试类,然后在该配置上定义testCompile依赖项。
我所有的Java项目都有这个代码块,它阻塞了所有测试代码:
task testJar(type: Jar, dependsOn: testClasses) {
    baseName = "test-${project.archivesBaseName}"
    from sourceSets.test.output
}
configurations {
    tests
}
artifacts {
    tests testJar
}
然后,当我有测试代码时,我想在我使用的项目之间进行访问
dependencies {
    testCompile project(path: ':aProject', configuration: 'tests')
}
这是针对Java的;我假设它也应该适用于常规。
configurations {       tests { extendsFrom testRuntime }     }
                    Could not get unknown property 'testClasses'
                    这是一个简单的解决方案,不需要中间的jar文件:
dependencies {
  ...
  testCompile project(':aProject').sourceSets.test.output
}
这个问题还有更多讨论:gradle的多项目测试依赖项
这对我有用(Java)
// use test classes from spring-common as dependency to tests of current module
testCompile files(this.project(':spring-common').sourceSets.test.output)
testCompile files(this.project(':spring-common').sourceSets.test.runtimeClasspath)
// filter dublicated dependency for IDEA export
def isClassesDependency(module) {
     (module instanceof org.gradle.plugins.ide.idea.model.ModuleLibrary) && module.classes.iterator()[0].url.toString().contains(rootProject.name)
}
idea {
      module {
          iml.whenMerged { module ->
              module.dependencies.removeAll(module.dependencies.grep{isClassesDependency(it)})
              module.dependencies*.exported = true
          }
      }
  }
.....  
// and somewhere to include test classes 
testRuntime project(":spring-common")
以上解决方案有效,但不适用于最新版本1.0-rc3的Gradle。
     task testJar(type: Jar, dependsOn: testClasses) {
       baseName = "test-${project.archivesBaseName}"
       // in the latest version of Gradle 1.0-rc3
       // sourceSets.test.classes no longer works
       // It has been replaced with 
       // sourceSets.test.output
       from sourceSets.test.output
     }
如果ProjectA包含您要在ProjectB中使用的测试代码,并且ProjectB要使用工件来包含测试代码,则ProjectB的build.gradle如下所示:
dependencies {
  testCompile("com.example:projecta:1.0.0-SNAPSHOT:tests")
}
然后,您需要向ProjectA的build.gradle中archives的artifacts部分添加命令:
task testsJar(type: Jar, dependsOn: testClasses) {
    classifier = 'tests'
    from sourceSets.test.output
}
configurations {
    tests
}
artifacts {
    tests testsJar
    archives testsJar
}
jar.finalizedBy(testsJar)
现在,当ProjectA的工件发布到您的工件时,它们将包含-tests jar。然后可以将此-tests jar添加为ProjectB的testCompile依赖项(如上所示)。
对于最新的gradle版本(我目前为2.14.1)上的Android,您只需在Project B中添加以下内容即可从Project A获得所有测试依赖项。
dependencies {
  androidTestComplie project(path: ':ProjectA')
}