Code Coverage with Gradle and Jacoco

Introduction

Samuel Addico
CodeOps
3 min readSep 17, 2018

--

So recently, I have was tasked to set up a Continuous Delivery pipeline for a number of applications at my place of work. The pipeline consisted of a number of steps including Checkout, Test, Code Coverage, Maven/Gradle Build, Push to Artifactory, Deploy to Stage Env and send a slack notification to the team. That's is pretty long, right? lol. I will probably blog on this later, but for today I will be sharing how I did the code coverage bit with Jacoco plugin. There are other tools like Cobertura and Sonarqube that serve the same purpose.

What is Code Coverage?

Code coverage is a measure of how much for your application’s code has been executed in testing. This covers not only seeing which lines of code have been executed but also checking that all branches have been covered. Code coverage is also called Test coverage. This gives developer teams reassurance that their programs have been broadly tested for bugs and should be relatively error-free.

What I did

Now let's zoom into action. So starting from Gradle 1.6, Jacoco plugin is supported, you just have to enable it. To enable it, add below in your build.gradle file.

apply plugin: 'jacoco'

Below is how the HTML output looks like

Now let come to them, even more, sweeter part of the cake:- enforcing code coverage metrics. What this means is that a threshold or rule is set for which a gradle task can be used to verify if code coverage metrics are met based on configured rules/threshold. The build fails if any of the configured rules are not met. JaCoCo only reports the first violated rule. See the example below.

jacocoTestCoverageVerification {
violationRules {
rule {
limit {
minimum = 0.7
}
}
}
}

When the jacocoTestCoverageVerification task is run, this rule will ensure that a code coverage metric of 70% met to be able to pass the build. To run coverage verification during the build (and fail when appropriate), you will need to add below again the build.gradle file

check.dependsOn jacocoTestCoverageVerification

Below is an example screenshot of a failed build.

This brings the curtains down on this session, I hope this helps someone out there. Feel free to leave a comment or correction. The source code for this session is hosted on my GitHub repository. Bye 🙂

References

Gradle Jacoco plugin

Originally published by samaddico at http://hashcod.wordpress.com on September 17, 2018.

--

--

Samuel Addico
CodeOps

DevOps | SRE | Java | Kubernetes | AWS | Ansible | Terraform | CI/CD