如何在gradle中创建自定义任务以将java和kotlin代码打包到jar中?

dma*_*rin 5 gradle kotlin

我们有一个多模块化设置,我们在模块之间共享一些测试类(主要是Fakes实现).我们当前的解决方案(您可以在下面找到)仅适用于用Java编写的类,但我们正在寻找支持共享的kotlin类.

if (isAndroidLibrary()) {
    task compileTestCommonJar(type: JavaCompile) {
        classpath = compileDebugUnitTestJavaWithJavac.classpath
        source sourceSets.testShared.java.srcDirs
        destinationDir = file('build/testCommon')
    }
    taskToDependOn = compileDebugUnitTestSources
} else {
    task compileTestCommonJar(type: JavaCompile) {
        classpath = compileTestJava.classpath
        source sourceSets.testShared.java.srcDirs
        destinationDir = file('build/testCommon')
    }
    taskToDependOn = testClasses
}

task testJar(type: Jar, dependsOn: taskToDependOn) {
    classifier = 'tests'
    from compileTestCommonJar.outputs
}
Run Code Online (Sandbox Code Playgroud)

我如何修改compileTestCommonJar它支持kotlin?

sed*_*vav 1

这是我们所做的:

  1. 在具有共享测试类的模块中,将test源集输出打包到 jar 中
configurations { tests }
...
task testJar(type: Jar, dependsOn: testClasses) {
    baseName = "test-${project.archivesBaseName}"
    from sourceSets.test.output
}

artifacts { tests testJar }
Run Code Online (Sandbox Code Playgroud)
  1. 在依赖于共享类的模块中
dependencies {
  testCompile project(path: ":my-project-with-shared-test-classes", configuration: "tests")
}
Run Code Online (Sandbox Code Playgroud)

PS:老实说,我更喜欢有一个单独的 Gradle 模块和通用测试类,因为它是更明确的解决方案。