DEV Community

Mikhail
Mikhail

Posted on

How to implement JaCoCo in Kotlin + Spring Boot + Gradle project

JaCoCo is a free code coverage library for Java, created by the EclEmma team. It is based on the lessons learned from using and integrating existing libraries for many years.
To use JaCoCo in your project you need to do:

  1. Add the JaCoCo plugin to the plugins section of the build.gradle.kts file in the root directory of your project.
plugins {
    ...
    id("jacoco")
}
Enter fullscreen mode Exit fullscreen mode
  1. Add JaCoCo's jacocoTestReport task and jacocoCoverageVerification task as finalizing a Test task. JaCoCo based on Java byte code and therefore you need to compile the bytecode of your application and test classes before running it.
tasks.withType<Test> {
    ....
    finalizedBy(tasks.jacocoTestReport, tasks.jacocoTestCoverageVerification)
}
Enter fullscreen mode Exit fullscreen mode
  1. Configure the violation rules for the jacocoVerificationCoverage task.
tasks.jacocoTestCoverageVerification {
    violationRules {
        rule {
            limit {
                minimum = "0.6".toBigDecimal()
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

To run JaCoCo, start gradle test task or gradle check task. This will build byte code for your application and test classes and run the tests. At the end of the Test task, JaCoCo will run its tasks, checking test coverage.

IntelliJ IDEA menu

The jacocoCoverageVerification task will print a report in the console.

> Task :jacocoTestReport
> Task :jacocoTestCoverageVerification FAILED
[ant:jacocoReport] Rule violated for bundle template: instructions covered ratio is 0.1, but expected minimum is 0.6
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':jacocoTestCoverageVerification'.
> Rule violated for bundle template: instructions covered ratio is 0.1, but expected minimum is 0.6
* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.
> Get more help at https://help.gradle.org.
BUILD FAILED in 13s
Enter fullscreen mode Exit fullscreen mode

The jacocoTestReport task will create a test report in HTML format that you can find in the project's built directory.

report-1

report-2

The entire code is available on GitHub.

Top comments (0)