我最近一直在思考这个问题,想就我几天前的想法获得一些反馈。
问题:
在典型的代码库中,每个模块都有一个 main
和一个 test
源集。这在一段时间内可以很好地工作,但迟早我总是会遇到这样的情况,我想将一堆类组合在一起,这样可以更轻松地测试涉及某个模块的代码。一个很好的例子是一组 hamcrest
给定模块的匹配器类。
假设 1:
作为hamcrest
是测试代码的库,这些匹配器不应该进入main
源集。假设 2: 这些类也不应该进入
test
源集,作为对test
的依赖source 只是这些类可用的一种解决方法。人们通常不希望依赖于实际测试。 也是not recommended (由 Netflix)定义对test
的依赖项目的源集。
解决方案 1:
在 main
中创建包含这些类的专用模块source-set 并在任何需要的地方简单地定义这个模块的测试依赖。
这是我使用了很长一段时间的方法,但我不太喜欢它。
首先,除了附加
testSupport
之外,我从来没有想出一个好听的名字。到原始模块的名称,导致名称类似于core-testSupport
,persistence-testSupport
等等。其次,它创建了大量模块,项目树被这些模块污染了。
解决方案 2:(我希望得到反馈的那个)
configurations {
testSupportCompile.extendsFrom compile
testSupportRuntime.extendsFrom runtime
}
sourceSets {
testSupport {
compileClasspath += sourceSets.main.output + configurations.testSupportCompile
runtimeClasspath += compileClasspath + configurations.testSupportRuntime
}
}
task testSupportJar(type: Jar) {
from sourceSets.testSupport.output
classifier 'testSupport'
}
artifacts {
testSupportCompile testSupportJar
}
上面的 gradle 配置可以放在名为 testSupport.gradle
的文件中并应用于需要此专用源集的任何模块,以提供可在测试中重用的类。
定义一个依赖会像这样工作:
testCompile project(path: ':core', configuration: 'testSupportCompile')
我对 gradle 还是个新手,研究了很多,但我仍然有几个问题。
我知道声明一个新的源集会自动创建两个配置:
<sourceSet>Compile
和<sourceSet>Runtime
.我不太喜欢这种方法的是,在声明依赖项时必须使用 testSupportCompile 配置。有没有办法将其别名为testSupport
还是类似的东西?我的项目目前可以正常编译。但是,我不确定我是否以正确的方式做事。如何改进此配置?
还有其他方法可以实现所需的功能吗?在研究过程中,我并没有真正找到关于这个主题的太多信息,这让我觉得我要么使用了错误的搜索词,要么做了一些根本不应该做的愚蠢事情。
我知道这是一个宽泛的问题,但我不确定除了此处之外,在哪里可以获得关于此类问题的适当反馈。
最佳答案
我有类似的情况,我已经推迟了一段时间的解决方案,使用了各种 hack 和变通方法。您的问题是调查它的最终动机。
这就是我最终得到的 -- EDIT 与 Thomas 合作完成的:
configurations {
// create a new configuration and inherit everything from compile
testlib.extendsFrom compile
}
sourceSets {
testlib {
// We will at least need access to our main sourceSet and all dependencies that are declared for our configuration.
compileClasspath += sourceSets.main.output + configurations.testlib
}
}
task testlibJar(type: Jar) {
from sourceSets.testlib.output
classifier 'testlib'
}
artifacts {
testlib testlibJar // include the classes into the new configuration
archives testlibJar // optional: include the support JAR into "uploadArchives", so it may also be used in other projects
}
然后,在依赖模块中,只需使用:
dependencies {
testCompile project(path: ':otherproject', configuration: 'testlib')
}
请注意,(空的)teSTLibCompile
和 teSTLibRuntime
配置仍会创建(作为引入新的 teSTLib
源集的结果),但我相信忽略它们是安全的。
另外,经常会遇到项目自己的test
配置需要使用teSTLib
(项目测试依赖通用测试支持)。在这种情况下,您可以在同一项目的两个配置之间添加依赖关系:
testCompile project(path: ':myproject', configuration: 'testlib')
或者单独增强编译和运行时类路径:
configurations {
testlib.extendsFrom compile
testCompile.extendsFrom testlib
}
sourceSets {
test {
compileClasspath += sourceSets.testlib.output
runtimeClasspath += sourceSets.testlib.output
}
}
关于testing - 反馈 `test-support`代码的gradle配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40600392/