2011-02-28 228 views
61

我有两个项目,项目A和项目B.两者都是用groovy编写的,并使用gradle作为构建系统。项目A需要项目B. 这适用于编译和测试代码。Gradle测试依赖关系

如何配置项目A的测试类可以访问项目B的测试类?

+2

可能重复:http://stackoverflow.com/questions/5644011/multi-project-test-dependencies-with-gradle – 2016-03-08 17:25:49

回答

87

您可以通过“测试”配置公开测试类,然后在该配置上定义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的;我假设它也适用于常规。

+0

难道就没有别的办法做到这一点,除了编译测试类? – djangofan 2012-12-08 03:21:59

+1

如果我理解你的问题,那么是的,据我所知,你需要编译测试类来使用它们作为依赖。 – 2012-12-31 19:47:33

+1

对于更高版本的Gradle(我正在使用1.3)“from sourceSets.test.classes”的行应该是“from sourceSets.test.output” – Ben 2013-01-28 20:06:24

5

上述解决方案可行,但不适用于Gradle的最新版本1.0-rc3

 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 
    } 
8

这对我的作品(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") 
0

对于摇篮1.5

task testJar(type: Jar, dependsOn: testClasses) { 
    from sourceSets.test.java 
    classifier "tests" 
} 
11

这是一个不需要中间jar文件一个简单的解决方案:

dependencies { 
    ... 
    testCompile project(':aProject').sourceSets.test.output 
} 

There' ■在这个问题更多的讨论:Multi-project test dependencies with gradle

+3

这打破了IDE集成并遗漏了传递依赖。它也打破了项目的封装,这总是一个不好的做法。 – 2017-02-20 17:40:19

1

对于Android的最新版本的Gradle(我目前在2.14.1),你只需要添加下面的项目B摆脱项目A.

中的所有测试的依赖
dependencies { 
    androidTestComplie project(path: ':ProjectA') 
}