It’s time to improve on the testing situation in Hahabit. I believe the coverage is low.

How low? Let’s add JaCoCo – the Java Code Coverage tool – to the project. I don’t think one should focus too hard on metrics like these, but they are fun to have. And if it’s really low, things are probably bad.

So we add the Gradle plugin:

plugins {
    // ...
    id "jacoco"
    // ...

And then you need to add some dependency settings manually:

 test {
    finalizedBy jacocoTestReport

jacocoTestReport {
    dependsOn test

Then I get a report in HTML whenever I run the tests. It looks like this:

JaCoCo report

I’m gonna track that 36% number, which is the number of instructions that are covered by tests, divided by the total number of instructions.

I’d like to get that number directly in the terminal, not having to open up an HTML file. JaCoCo has some different report options, XML and CSV. Unfortunately no JSON. I’m gonna do what I saw someone do at work, get the CSV report and parse it with awk.

So, I make my jacocoTestReport section in build.gradle look like this:

jacocoTestReport {
    dependsOn test
    reports {
        csv.required = true

We can then run the tests and get the coverage number:

$ ./gradlew test jacocoTestReport

6 actionable tasks: 2 executed, 4 up-to-date

It then puts a CSV file in build/reports/jacoco/test/jacocoTestReport.csv:

$ cat build/reports/jacoco/test/jacocoTestReport.csv

We want to sum up the INSTRUCTION_COVERED and INSTRUCTION_MISSED columns.

This is the kind of problem where the teacher asks “allright, who can do this?” and awk is like “me!! meee!! I can do this!!”. And Python rolls their eyes and goes like “yeah, wow? You can add up some numbers? I can add up numbers. You want it as a one-liner? I’ll give you a one-liner” and the others are like “oh, come on Python, let awk have this moment”. Perl is just sitting in a corner looking smug.

So yeah, let’s let awk do it. I’m putting this in a script.

#!/usr/bin/env bash
./gradlew jacocoTestReport
awk -F, \
    '{ total += $4 + $5; covered += $5 } END { print "Coverage: " 100*covered/total "%" }' \

And then just:

$ ./

6 actionable tasks: 6 up-to-date

Coverage: 36.803%

Nice. If I were a better Gradle hacker, I’d make this run as some kind of hook in the Gradle file itself. But I’m happy with this for now.

Continue reading part thirty-two.