Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a custom task in gradle to pack java and kotlin code to a jar?

Tags:

gradle

kotlin

We have a multi modular setup and we are sharing some tests classes between the modules (mainly Fakes implementations). Our current solution (that you can find below) works just for classes written in Java, but we are looking at supporting also shared kotlin classes.

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
}

How can I modify the compileTestCommonJar so it supports kotlin?

like image 708
dmarin Avatar asked Nov 07 '22 04:11

dmarin


1 Answers

Here is what we do:

  1. In the module with shared test classes, pack the test source set output into a jar
configurations { tests }
...
task testJar(type: Jar, dependsOn: testClasses) {
    baseName = "test-${project.archivesBaseName}"
    from sourceSets.test.output
}

artifacts { tests testJar }
  1. In a module that depends on the shared classes
dependencies {
  testCompile project(path: ":my-project-with-shared-test-classes", configuration: "tests")
}

PS: Honestly, I would prefer to have a separate Gradle module with common test classes as it's more explicit solution.

like image 177
sedovav Avatar answered Nov 29 '22 11:11

sedovav