2011-02-28 269 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') 
}