Code coverage

suggest change

Code coverage tells you which lines and branches of your code ran during tests. It doesn't tell you whether the tests check the right things, but it is very good at showing code that no test runs at all.

For Kotlin on the JVM there are two main tools:

Both work the same way. A Java agent instruments classes as they are loaded, the tests run, and the agent records which bytecode ran. A report task then maps that data back to source lines.

This article uses Gradle with the Kotlin DSL. For running tests themselves see Testing in CI and Parameterized tests.

Code under test

All examples measure this small pricing module, src/main/kotlin/shop/Pricing.kt:

package shop

enum class Tier { BASIC, SILVER, GOLD }

fun discountPercent(tier: Tier, total: Int): Int {
    require(total >= 0) { "total must not be negative" }
    return when (tier) {
        Tier.BASIC -> if (total >= 100) 5 else 0
        Tier.SILVER -> 10
        Tier.GOLD -> if (total >= 100) 20 else 15
    }
}

fun finalPrice(tier: Tier, total: Int): Int =
    total - total * discountPercent(tier, total) / 100

We start with only two tests in src/test/kotlin/shop/PricingTest.kt:

package shop

import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test

class PricingTest {
    @Test
    fun basicCustomerGetsFivePercentOverHundred() {
        assertEquals(95, finalPrice(Tier.BASIC, 100))
    }

    @Test
    fun silverCustomerAlwaysGetsTenPercent() {
        assertEquals(10, discountPercent(Tier.SILVER, 50))
    }
}

Both tests pass, but they skip the GOLD tier, the "under 100" path for BASIC, and the negative total check.

Kover: setup

Apply the plugin in build.gradle.kts. You don't need any other configuration to get a report:

plugins {
    kotlin("jvm") version "2.4.21"
    id("org.jetbrains.kotlinx.kover") version "0.9.11"
}

repositories {
    mavenCentral()
}

dependencies {
    testImplementation(platform("org.junit:junit-bom:6.1.3"))
    testImplementation("org.junit.jupiter:junit-jupiter")
    testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}

tasks.test {
    useJUnitPlatform()
}

Kover adds these tasks. Each one runs the tests first if needed:

Task Output
koverLog coverage summary printed to the console
koverHtmlReport build/reports/kover/html/index.html
koverXmlReport build/reports/kover/report.xml (JaCoCo XML format)
koverBinaryReport build/reports/kover/report.ic (raw binary data)
koverVerify fails the build if coverage rules are violated

The quickest check prints a single number:

./gradlew koverLog
Application line coverage: 85.7143%

Six of the seven executable lines ran. Line coverage hides a lot, though. The if on the BASIC line counts as covered even though only one of its branches ran.

The HTML report shows each source file with fully covered lines in green, partly covered lines in yellow and uncovered lines in red. Open build/reports/kover/html/index.html in a browser after running ./gradlew koverHtmlReport.

Kover: per-class console summary

You can change what koverLog prints. Here it groups the results by class:

import kotlinx.kover.gradle.plugin.dsl.CoverageUnit
import kotlinx.kover.gradle.plugin.dsl.GroupingEntityType

kover {
    reports {
        total {
            log {
                header = "Coverage summary"
                format = "<entity> line coverage: <value>%"
                groupBy = GroupingEntityType.CLASS
                coverageUnits = CoverageUnit.LINE
            }
        }
    }
}
Coverage summary
shop.PricingKt line coverage: 83.3333%
shop.Tier line coverage: 100%

Top-level functions in Pricing.kt compile to a class named PricingKt, so that is the name the report uses.

Kover: enforcing a minimum

To make coverage part of the build, add verification rules. koverVerify checks them, and Kover also makes the standard check task depend on koverVerify, so ./gradlew check and ./gradlew build enforce them too:

kover {
    reports {
        total {
            verify {
                rule("Minimal line coverage") {
                    minBound(90) // percent of lines
                }
                rule("Branch coverage") {
                    bound {
                        minValue = 80
                        coverageUnits = CoverageUnit.BRANCH
                    }
                }
            }
        }
    }
}

With the two tests above the build fails:

./gradlew check
> Task :koverVerify FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':koverVerify' (registered by plugin 'org.jetbrains.kotlinx.kover').
> Rule 'Minimal line coverage' violated: lines covered percentage is 85.714300, but expected minimum is 90
  Rule 'Branch coverage' violated: branches covered percentage is 55.555600, but expected minimum is 80

The branch number shows the real gap. Only 5 of 9 branches ran.

Filling the gaps

The report shows exactly which tests are missing. Add them:

package shop

import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows

class PricingTest {
    @Test
    fun basicCustomerGetsFivePercentOverHundred() {
        assertEquals(95, finalPrice(Tier.BASIC, 100))
    }

    @Test
    fun basicCustomerGetsNothingUnderHundred() {
        assertEquals(0, discountPercent(Tier.BASIC, 99))
    }

    @Test
    fun silverCustomerAlwaysGetsTenPercent() {
        assertEquals(10, discountPercent(Tier.SILVER, 50))
    }

    @Test
    fun goldDiscountDependsOnTotal() {
        assertEquals(15, discountPercent(Tier.GOLD, 50))
        assertEquals(20, discountPercent(Tier.GOLD, 200))
    }

    @Test
    fun negativeTotalIsRejected() {
        assertThrows<IllegalArgumentException> { discountPercent(Tier.GOLD, -1) }
    }

    @Test
    fun receiptComputesPrice() {
        assertEquals(160, Receipt(Tier.GOLD, 200).price)
    }
}

Each new test is aimed at a branch, not just a line. The thresholds are there to point you at untested behavior. Writing assertion-free tests just to raise the number defeats the purpose.

Excluding code from coverage

Real projects contain code that isn't worth unit testing, such as main functions, generated code and debug helpers. Say the project also has a CLI entry point and a debug method:

// src/main/kotlin/shop/cli/Main.kt
package shop.cli

import shop.Receipt
import shop.Tier

fun main(args: Array<String>) {
    val tier = Tier.valueOf(args.getOrElse(0) { "BASIC" })
    val total = args.getOrElse(1) { "0" }.toInt()
    println(Receipt(tier, total).price)
}
// src/main/kotlin/shop/Receipt.kt
package shop

data class Receipt(val tier: Tier, val total: Int) {
    val price: Int get() = finalPrice(tier, total)

    @ExcludeFromCoverage
    fun debugDump(): String = "Receipt(tier=$tier, total=$total, price=$price)"
}

Before any filtering, the untested code pulls the totals down:

Coverage summary
shop.PricingKt line coverage: 100%
shop.Receipt line coverage: 66.6667%
shop.Tier line coverage: 100%
shop.cli.MainKt line coverage: 0%
> Rule 'Minimal line coverage' violated: lines covered percentage is 69.230800, but expected minimum is 90
  Rule 'Branch coverage' violated: branches covered percentage is 55.555600, but expected minimum is 80

Kover can exclude code by package, by class name pattern, by annotation, or by supertype. To exclude by annotation, declare your own marker annotation. It needs at least BINARY retention so it ends up in the class file:

package shop

@Retention(AnnotationRetention.BINARY)
@Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION)
annotation class ExcludeFromCoverage

Then add filters that apply to all reports:

kover {
    reports {
        filters {
            excludes {
                packages("shop.cli")
                annotatedBy("shop.ExcludeFromCoverage")
                // other options:
                // classes("*.BuildConfig", "*Generated*")
                // inheritedFrom("java.lang.Exception")
            }
        }
        total {
            // log { ... } and verify { ... } as before
        }
    }
}
Coverage summary
shop.PricingKt line coverage: 100%
shop.Receipt line coverage: 100%
shop.Tier line coverage: 100%

koverVerify now passes. Notice that the data class didn't need any special treatment. The compiler-generated equals, hashCode, toString, copy and componentN methods are not counted as missed code.

Keep exclusions narrow and easy to see. If whole packages disappear from the report, nobody will notice when real logic ends up in them.

Kover with the JaCoCo engine

By default Kover uses the IntelliJ coverage agent. If your tooling expects numbers that match JaCoCo exactly, switch engines with one line. The DSL, filters and task names stay the same:

kover {
    useJacoco("0.8.15")
}

The two engines can count branches differently for the same code. Run the same engine locally and in CI so that thresholds mean the same thing everywhere.

Multi-module projects

Every module that applies the Kover plugin measures its own coverage. To get one combined report, apply the plugin in the root project too and list the modules as kover dependencies:

// root build.gradle.kts
plugins {
    id("org.jetbrains.kotlinx.kover") version "0.9.11"
}

repositories {
    mavenCentral() // Kover downloads its reporter from here
}

dependencies {
    kover(project(":core"))
    kover(project(":api"))
}

./gradlew :koverHtmlReport in the root then covers the classes of all listed modules, and tests in one module count toward coverage of another. A module's own report (./gradlew :core:koverLog) counts only the tests in that module.

JaCoCo with the Gradle plugin

Gradle has a built-in jacoco plugin. It adds jacocoTestReport and jacocoTestCoverageVerification tasks. Neither runs by default, so you have to wire them in yourself:

plugins {
    kotlin("jvm") version "2.4.21"
    jacoco
}

repositories {
    mavenCentral()
}

dependencies {
    testImplementation(platform("org.junit:junit-bom:6.1.3"))
    testImplementation("org.junit.jupiter:junit-jupiter")
    testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}

jacoco {
    toolVersion = "0.8.15"
}

val coverageExcludes = listOf("shop/cli/**")

tasks.test {
    useJUnitPlatform()
    finalizedBy(tasks.jacocoTestReport) // report after every test run
}

tasks.jacocoTestReport {
    dependsOn(tasks.test)
    reports {
        xml.required = true   // for Codecov, Sonar, PR bots
        html.required = true  // for humans
        csv.required = true   // for scripts
    }
    classDirectories.setFrom(
        files(classDirectories.files.map { fileTree(it) { exclude(coverageExcludes) } })
    )
}

tasks.jacocoTestCoverageVerification {
    violationRules {
        rule {
            limit {
                counter = "LINE"
                minimum = "0.90".toBigDecimal()
            }
            limit {
                counter = "BRANCH"
                minimum = "0.80".toBigDecimal()
            }
        }
        rule {
            element = "CLASS"            // check each class separately
            excludes = listOf("shop.Tier")
            limit {
                counter = "LINE"
                minimum = "0.75".toBigDecimal()
            }
        }
    }
    classDirectories.setFrom(tasks.jacocoTestReport.map { it.classDirectories })
}

tasks.check {
    dependsOn(tasks.jacocoTestCoverageVerification)
}

Unlike Kover, JaCoCo excludes by class file path (shop/cli/**), not by package name. Apply the same filter to both tasks, or the verification will still count the excluded classes.

JaCoCo has no annotatedBy option. Instead it skips any class or method annotated with an annotation whose simple name contains Generated and whose retention is BINARY or RUNTIME. Rename the marker annotation and it works with no configuration:

package shop

@Retention(AnnotationRetention.BINARY)
@Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION)
annotation class Generated

After ./gradlew check, build/reports/jacoco/test/jacocoTestReport.csv contains:

GROUP,PACKAGE,CLASS,INSTRUCTION_MISSED,INSTRUCTION_COVERED,BRANCH_MISSED,BRANCH_COVERED,LINE_MISSED,LINE_COVERED,COMPLEXITY_MISSED,COMPLEXITY_COVERED,METHOD_MISSED,METHOD_COVERED
shop,shop,Tier,0,25,0,0,0,1,0,1,0,1
shop,shop,PricingKt,0,47,0,11,0,6,0,8,0,2
shop,shop,Receipt,6,15,0,0,0,2,2,2,2,2

The two missed methods in Receipt are the getTier() and getTotal() property getters. No test reads tier or total directly. They live on the constructor line, which ran, so line coverage is still 100%. debugDump is excluded by @Generated, and the data class methods are filtered as compiler-generated.

JaCoCo without Gradle

The JaCoCo agent and CLI are plain jars, so you can measure any JVM process, including a jar started from a script. Compile the main and test code separately so that tests don't end up in the report:

kotlinc src/main -d out/main
kotlinc src/test -cp "out/main:junit-platform-console-standalone-6.1.3.jar" -d out/test

java -javaagent:org.jacoco.agent-0.8.15-runtime.jar=destfile=jacoco.exec \
  -jar junit-platform-console-standalone-6.1.3.jar execute \
  --class-path "out/main:out/test:$KOTLIN_HOME/lib/kotlin-stdlib.jar" \
  --select-package shop

java -jar org.jacoco.cli-0.8.15-nodeps.jar report jacoco.exec \
  --classfiles out/main --sourcefiles src/main \
  --csv report.csv --html html

On Windows use ; instead of : to separate class path entries. --sourcefiles must point at the source root (the directory that contains shop/) so that JaCoCo can match package shop to the files. With the original two tests the CSV report is:

GROUP,PACKAGE,CLASS,INSTRUCTION_MISSED,INSTRUCTION_COVERED,BRANCH_MISSED,BRANCH_COVERED,LINE_MISSED,LINE_COVERED,COMPLEXITY_MISSED,COMPLEXITY_COVERED,METHOD_MISSED,METHOD_COVERED
JaCoCo Coverage Report,shop,Tier,0,25,0,0,0,1,0,1,0,1
JaCoCo Coverage Report,shop,PricingKt,18,29,6,5,1,5,5,3,0,2

The HTML page for Pricing.kt marks each line and shows a tooltip with the branch counts:

L6   partly    2 of 4 branches missed.   require(total >= 0) { "total must not be negative" }
L7   partly    1 of 3 branches missed.   return when (tier) {
L8   partly    1 of 2 branches missed.   Tier.BASIC -> if (total >= 100) 5 else 0
L9   covered                             Tier.SILVER -> 10
L10  missed    All 2 branches missed.    Tier.GOLD -> if (total >= 100) 20 else 15

Here JaCoCo counts 11 branches where Kover counted 9. require is an inline function, and its inlined check adds branches on line 6. The missed ones are the failure path, the code that throws, so the result is still useful: a test for invalid input is missing.

Coverage in CI

Both tools write JaCoCo-format XML, which coverage services understand. A GitHub Actions job using Kover:

name: Coverage

on: [push, pull_request]

jobs:
  coverage:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v5
      - uses: actions/setup-java@v5
        with:
          distribution: temurin
          java-version: '21'
      - uses: gradle/actions/setup-gradle@v5

      # runs tests, fails on coverage rule violations, writes the XML report
      - run: ./gradlew check koverXmlReport

      - uses: codecov/codecov-action@v5
        if: always()
        with:
          files: build/reports/kover/report.xml
          token: ${{ secrets.CODECOV_TOKEN }}

      - uses: actions/upload-artifact@v4
        if: always()
        with:
          name: coverage-html
          path: build/reports/kover/html/

For JaCoCo, use ./gradlew check and the path build/reports/jacoco/test/jacocoTestReport.xml.

Kotlin-specific notes

Practical advice

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents