0
0
JUnittesting~5 mins

Coverage thresholds in JUnit

Choose your learning style9 modes available
Introduction

Coverage thresholds help ensure your tests check enough of your code. They warn you if tests miss important parts.

When you want to make sure your tests cover at least 80% of your code.
When you add new features and want to keep test quality high.
When you want to avoid releasing code with untested parts.
When your team agrees on minimum test coverage standards.
When you want automated checks to fail builds if coverage is too low.
Syntax
JUnit
jacoco {
    toolVersion = '0.8.8'
}
test {
    finalizedBy jacocoTestReport
}
jacocoTestReport {
    dependsOn test
    reports {
        xml.required.set(true)
        html.required.set(true)
    }
}
jacocoTestCoverageVerification {
    violationRules {
        rule {
            limit {
                minimum = 0.80
            }
        }
    }
}
check.dependsOn jacocoTestCoverageVerification

This example uses JaCoCo with Gradle and JUnit.

The minimum value is the coverage threshold (80% here).

Examples
Set coverage threshold to 90%.
JUnit
limit {
    minimum = 0.90
}
Set coverage threshold to 75% for a less strict check.
JUnit
limit {
    minimum = 0.75
}
Disable a coverage rule temporarily.
JUnit
rule {
    enabled = false
}
Sample Program

This Gradle build script sets up JUnit tests with JaCoCo coverage. It requires at least 80% coverage. If coverage is below 80%, the build fails.

JUnit
plugins {
    id 'java'
    id 'jacoco'
}

repositories {
    mavenCentral()
}

dependencies {
    testImplementation 'org.junit.jupiter:junit-jupiter:5.9.2'
}

jacoco {
    toolVersion = '0.8.8'
}

test {
    useJUnitPlatform()
    finalizedBy jacocoTestReport
}

jacocoTestReport {
    dependsOn test
    reports {
        xml.required.set(true)
        html.required.set(true)
    }
}

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

check.dependsOn jacocoTestCoverageVerification
OutputSuccess
Important Notes

Coverage thresholds help catch missing tests early.

Set realistic thresholds to avoid blocking progress.

Use reports to see which code is not covered.

Summary

Coverage thresholds set minimum test coverage levels.

They help keep tests thorough and code reliable.

Use tools like JaCoCo with JUnit to enforce thresholds automatically.