关于`test-support`代码

时间:2016-11-15 01:00:51

标签: testing gradle multi-project

我最近一直在考虑这个问题,并希望得到一些关于我几天前的想法的反馈。

问题:

在典型的代码库中,每个模块都有maintest源集。这可以在一段时间内很好地工作但是迟早我总是偶然发现我希望将一组类组合在一起的情况,这些类允许更容易地测试涉及特定模块的代码。一个很好的例子是给定模块的一组hamcrest匹配器类。

  • 假设1:
    由于hamcrest是测试代码库,因此这些匹配器不应进入main源代码集。

  • 假设2: 这些类也不应该进入test源集,因为对test源的依赖只是这些类可用的解决方法。人们通常不希望依赖于实际测试。 它也是not recommended(由Netflix提供)来定义对项目的test源集的依赖。

解决方案1 ​​

main源集中创建一个包含这些类的专用模块,只需在需要它们的地方定义对该模块的测试依赖性。

这是我现在用了很长时间的方法,但我并不喜欢它。

  • 首先,除了将testSupport附加到原始模块的名称之外,我从未想出一个好名字,这会导致core-testSupportpersistence-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')

我仍然有点新手并且经常研究,但我仍然有几个问题。

  1. 我了解声明新的源集会自动创建两个配置:<sourceSet>Compile<sourceSet>Runtime。我真的不喜欢这种方法,在声明依赖关系时必须使用testSupport 编译配置。有没有办法将此别名改为testSupport或类似的东西?

  2. 我的项目目前编译得很好。但是,我不确定我是否正确地做事。如何改进这种配置?

  3. 有没有其他方法可以实现所需的功能?在研究的时候,我并没有真正发现这个话题,这让我觉得我要么使用错误的搜索术语,要么做一些不应该做的愚蠢的事情。

  4. 我知道这是一个广泛的问题,但我不知道在哪里可以得到适当的反馈,除了这里。

1 个答案:

答案 0 :(得分:1)

我有类似的情况,我已经推迟了一段时间的解决方案,使用各种黑客和解决方法。你的问题是调查它的最终动机。

这是我与托马斯合作的最终结果 - EDIT

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')
}

请注意,仍然会创建(空)testlibCompiletestlibRuntime配置(因为引入了新的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
    }
}