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:
- Add the JaCoCo plugin to the
plugins
section of thebuild.gradle.kts
file in the root directory of your project.
plugins {
...
id("jacoco")
}
- Add JaCoCo's
jacocoTestReport
task andjacocoCoverageVerification
task as finalizing aTest
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)
}
- Configure the violation rules for the
jacocoVerificationCoverage
task.
tasks.jacocoTestCoverageVerification {
violationRules {
rule {
limit {
minimum = "0.6".toBigDecimal()
}
}
}
}
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.
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
The jacocoTestReport
task will create a test report in HTML format that you can find in the project's built directory.
The entire code is available on GitHub.
Top comments (0)