Skip to content

Instantly share code, notes, and snippets.

@alexvanyo
Last active August 29, 2024 09:09
Show Gist options
  • Save alexvanyo/9a3b38ef6c07907cfa7f9a4310c628bd to your computer and use it in GitHub Desktop.
Save alexvanyo/9a3b38ef6c07907cfa7f9a4310c628bd to your computer and use it in GitHub Desktop.
Kotlin DSL JaCoCo configuration for Android
import com.android.build.gradle.internal.tasks.factory.dependsOn
plugins {
id("com.android.application")
jacoco
}
// Register the main JaCoCo task to later depend on the per-variant tasks
val jacocoTestReport = tasks.register("jacocoTestReport")
tasks.withType<Test> {
configure<JacocoTaskExtension> {
isIncludeNoLocationClasses = true
}
}
android {
applicationVariants.all(closureOf<com.android.build.gradle.api.ApplicationVariant> {
val testTaskName = "test${[email protected]()}UnitTest"
val excludes = listOf(
// Android
"**/R.class",
"**/R\$*.class",
"**/BuildConfig.*",
"**/Manifest*.*"
)
val reportTask = tasks.register("jacoco${testTaskName.capitalize()}Report", JacocoReport::class) {
dependsOn(testTaskName)
reports {
xml.isEnabled = true
html.isEnabled = true
}
classDirectories.setFrom(
files(
fileTree([email protected]().destinationDir) {
exclude(excludes)
},
fileTree("$buildDir/tmp/kotlin-classes/${[email protected]}") {
exclude(excludes)
}
)
)
// Code underneath /src/{variant}/kotlin will also be picked up here
sourceDirectories.setFrom([email protected] { it.javaDirectories })
executionData.setFrom(file("$buildDir/jacoco/$testTaskName.exec"))
}
jacocoTestReport.dependsOn(reportTask)
})
}
@DenisShov
Copy link

For other people who wonder why apply(from - "../jacoco.gradle.kts") doesn't work, check this article - https://medium.com/@kurtlemond/migrating-jacoco-reports-gradle-tasks-to-kotlin-dsl-7b566d89ea92

TLDR: Dynamic resolution, which Groovy DSL provides, does not exists in Kotlin DSL.

I ended up using "Precompiled Script Plugin".

I just added kotlin-dsl-precompiled-script-plugins to buildSrc/build.gradle.kts and created jacoco-reports.gradle.kts under buildSrc/src/main/kotlin folder. Then you can add id("jacoco-reports") plugin to your modules.

@rontho
Copy link

rontho commented Feb 29, 2024

@DenisShov other solution would be to revert jacoco.gradle.kts to groovy right ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment