TExcelTAD
Home › Java Builds: Maven & Gradle › Tests & JaCoCo Coverage

Tests & JaCoCo Coverage

The java plugin's test task runs the tests of the test source set in a separate JVM. Three settings need to be right in every build, and the JaCoCo plugin adds coverage on top.

Setting up JUnit 5

kotlin
dependencies {
    testImplementation(platform("org.junit:junit-bom:5.14.4"))
    testImplementation("org.junit.jupiter:junit-jupiter")
    testRuntimeOnly("org.junit.platform:junit-platform-launcher")   // required since Gradle 9
}
tasks.test {
    useJUnitPlatform()          // without it, Gradle looks for JUnit 4 tests and finds none
}

Forget useJUnitPlatform() and Gradle looks for JUnit 4 tests and finds none; older Gradle versions then reported a green build with zero tests, and Gradle 9 fails instead (the test task did not discover any tests to execute, controlled by failOnNoDiscoveredTests). Forget the launcher and Gradle 9 fails with Failed to load JUnit Platform. The exercises let you meet both errors.

Seeing results

By default Gradle prints nothing for passing tests and a summary for failures. testLogging chooses which events reach the console:

bash · try it yourself
mkdir -p t/src/main/java/demo t/src/test/java/demo && cd t
echo 'rootProject.name = "t"' > settings.gradle.kts
cat > build.gradle.kts <<'KTS'
plugins { java }
repositories { mavenCentral() }
dependencies {
    testImplementation(platform("org.junit:junit-bom:5.14.4"))
    testImplementation("org.junit.jupiter:junit-jupiter")
    testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}
tasks.test {
    useJUnitPlatform()
    testLogging {
        events("passed", "skipped", "failed")
        exceptionFormat = org.gradle.api.tasks.testing.logging.TestExceptionFormat.SHORT
    }
}
KTS
cat > src/main/java/demo/Discount.java <<'SRC'
package demo;

public class Discount {
    public static int apply(int cents, int percent) {
        if (percent < 0 || percent > 100) throw new IllegalArgumentException("percent " + percent);
        return cents - cents * percent / 100;
    }
}
SRC
cat > src/test/java/demo/DiscountTest.java <<'SRC'
package demo;

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

class DiscountTest {
    @Test void tenPercent() { assertEquals(900, Discount.apply(1000, 10)); }
    @Test void rejectsNegative() { assertThrows(IllegalArgumentException.class, () -> Discount.apply(1000, -5)); }
    @Test void roundsDown() { assertEquals(333, Discount.apply(999, 66)); }
}
SRC
gradle test 2>&1 | grep -E 'DiscountTest|tests completed|expected|FAILED$|BUILD'
ls build/test-results/test
> Task :test FAILED
DiscountTest > roundsDown() FAILED
    org.opentest4j.AssertionFailedError at DiscountTest.java:10
DiscountTest > rejectsNegative() PASSED
DiscountTest > tenPercent() PASSED
3 tests completed, 1 failed
BUILD FAILED in 10s
TEST-demo.DiscountTest.xml
binary

roundsDown fails (999 − 659 = 340, not 333). With the SHORT format Gradle prints the exception type and test line (FULL adds the expected: <333> but was: <340> message and stack), links the HTML report in build/reports/tests/test/, and writes JUnit XML files to build/test-results/test/ for CI, the same format as Surefire's. Rerunning gradle test after a failure runs the tests again (a failed task is never up to date); after a success, an unchanged test task is UP-TO-DATE. gradle test --tests 'demo.DiscountTest.tenPercent' selects tests, and --rerun forces one task to run again.

JaCoCo coverage

The jacoco plugin attaches the JaCoCo agent to the test JVM and adds jacocoTestReport (HTML, XML, CSV) and jacocoTestCoverageVerification (fails below a threshold):

bash · try it yourself
mkdir -p cov/src/main/java/demo cov/src/test/java/demo && cd cov
echo 'rootProject.name = "cov"' > settings.gradle.kts
cat > build.gradle.kts <<'KTS'
plugins { java; jacoco }
repositories { mavenCentral() }
dependencies {
    testImplementation(platform("org.junit:junit-bom:5.14.4"))
    testImplementation("org.junit.jupiter:junit-jupiter")
    testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}
tasks.test {
    useJUnitPlatform()
    finalizedBy(tasks.jacocoTestReport)
}
tasks.jacocoTestReport {
    reports { csv.required = true }
}
tasks.jacocoTestCoverageVerification {
    violationRules { rule { limit { minimum = "0.80".toBigDecimal() } } }
}
KTS
cat > src/main/java/demo/Discount.java <<'SRC'
package demo;

public class Discount {
    public static int apply(int cents, int percent) {
        if (percent < 0 || percent > 100) throw new IllegalArgumentException("percent " + percent);
        return cents - cents * percent / 100;
    }

    public static String label(int percent) {
        return percent == 0 ? "full price" : percent + "% off";
    }
}
SRC
cat > src/test/java/demo/DiscountTest.java <<'SRC'
package demo;

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

class DiscountTest {
    @Test void tenPercent() { assertEquals(900, Discount.apply(1000, 10)); }
}
SRC
gradle test | grep '^> Task :jacoco'
awk -F, 'NR==1 { print "class      instructions  branches  lines   (missed/covered)"; next }
         { printf "%-10s %-13s %-9s %s\n", $3, $4"/"$5, $6"/"$7, $8"/"$9 }' build/reports/jacoco/test/jacocoTestReport.csv
gradle jacocoTestCoverageVerification 2>&1 | grep -E 'Rule violated|BUILD'
> Task :jacocoTestReport
class      instructions  branches  lines   (missed/covered)
Discount   16/13         4/2       2/2
[ant:jacocoReport] Rule violated for bundle cov: instructions covered ratio is 0.44, but expected minimum is 0.80
   > Rule violated for bundle cov: instructions covered ratio is 0.44, but expected minimum is 0.80
BUILD FAILED in 949ms

The CSV shows what one test missed: the exception branch and the whole label method. The verification task turns that into a failing build, with the measured ratio in the message. Add it to check (tasks.check { dependsOn(tasks.jacocoTestCoverageVerification) }) to enforce it on every gradle build.

Tip: Coverage thresholds work best as a ratchet on new code, not a global target. Develocity, Codecov and SonarQube read the JaCoCo XML report (reports { xml.required = true }) and comment on pull requests. For Maven, the jacoco-maven-plugin provides the same prepare-agent/report/check goals.

Test yourself

Gradle 9 fails with "the test task did not discover any tests to execute" although JUnit 5 tests exist. What is the most likely cause?

  1. The tests are too fast
  2. useJUnitPlatform() is missing from the test task
  3. jacoco is not applied
  4. The build cache was used

Where does Gradle write JUnit XML results for CI?

  1. build/libs
  2. build/test-results/test
  3. target/surefire-reports
  4. .gradle/

Which task fails the build when coverage is below a rule's minimum?

  1. jacocoTestReport
  2. jacocoTestCoverageVerification
  3. test
  4. check by default