首页 > 解决方案 > 如何在 gradle 中创建自定义任务以将 java 和 kotlin 代码打包到 jar 中?

问题描述

我们有一个多模块设置,我们在模块之间共享一些测试类(主要是 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
}

如何修改compileTestCommonJar它以支持 kotlin?

标签: gradlekotlin

解决方案


这是我们所做的:

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

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

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


推荐阅读