Test Reports, Code Coverage and Quality Gates: JUnit, JaCoCo, Warnings, SonarQube and Trivy
Quality Gates: The Idea
A quality gate is a rule that says: *if this check is not good enough, the pipeline must not continue*. Without gates, CI only tells you that the code compiles. With gates, it tells you that the code is tested, clean and safe enough to release.
| Check | Tool | Typical rule |
| Unit tests | JUnit, pytest, Jest, xUnit | All pass |
| Coverage | JaCoCo, Cobertura, Coverage plugin | At least 80 percent on new code |
| Static analysis | Checkstyle, SpotBugs, ESLint, Ruff, SonarQube | No new critical issues |
| Dependency vulnerabilities | OWASP Dependency-Check, Trivy, npm audit | No fixed critical or high |
| Container image scan | Trivy, Grype, Docker Scout | No fixed critical or high |
| Secrets scan | Gitleaks, Trivy | None found |
| License check | License Finder, FOSSA | No banned licenses |
Publish Test Results
groovy
post {
always {
junit testResults: '**/target/surefire-reports/*.xml',
allowEmptyResults: false,
skipPublishingChecks: false
}
}
- Jenkins shows pass, fail and skip counts, a trend graph, and the failing tests with their output
- If tests fail,
junit marks the build UNSTABLE (yellow) by default. To make failed tests a hard failure, add error('tests failed') when currentBuild.result == 'UNSTABLE', or use skipMarkingBuildUnstable and your own logic
allowEmptyResults: false makes the build fail if no report files are found, which catches broken test setups
groovy
stage('Gate: tests') {
steps {
script {
if (currentBuild.result == 'UNSTABLE') {
error 'Unit tests failed: stopping the pipeline'
}
}
}
}
Coverage
Use the Coverage plugin (successor of the older code coverage plugins) to publish JaCoCo, Cobertura or other reports and to set thresholds.
groovy
recordCoverage(
tools: [[parser: 'JACOCO', pattern: '**/target/site/jacoco/jacoco.xml']],
id: 'jacoco', name: 'JaCoCo Coverage',
sourceCodeRetention: 'EVERY_BUILD',
qualityGates: [
[threshold: 80.0, metric: 'LINE', baseline: 'PROJECT', unstable: true],
[threshold: 70.0, metric: 'BRANCH', baseline: 'PROJECT', unstable: true],
[threshold: 85.0, metric: 'LINE', baseline: 'MODIFIED_LINES', unstable: false]
]
)
| Baseline | Meaning |
PROJECT | Coverage of the whole project |
MODIFIED_FILES, MODIFIED_LINES | Only the changed files or lines (needs a reference build) |
PROJECT_DELTA | Change compared to the reference build |
Gate on new code: Demanding 80 percent on the whole of an old project is often impossible. Demand a good level on new and changed code so quality only goes up.
Static Analysis With Warnings Next Generation
groovy
stage('Static analysis') {
steps {
sh 'mvn -B checkstyle:checkstyle spotbugs:spotbugs'
}
post {
always {
recordIssues(
enabledForFailure: true,
tools: [checkStyle(pattern: '**/checkstyle-result.xml'), spotBugs(pattern: '**/spotbugsXml.xml')],
qualityGates: [[threshold: 1, type: 'NEW_HIGH', unstable: false],
[threshold: 20, type: 'TOTAL', unstable: true]]
)
}
}
}
NEW_HIGH, NEW, TOTAL, DELTA are the common gate types
- A
reference build (usually the target branch) lets Jenkins show only new issues in a pull request
SonarQube Quality Gate
- Run SonarQube (or SonarCloud) and create a project token; store it as secret text
sonar-token
- Install the SonarQube Scanner plugin and in *Manage Jenkins, System* add the server (name
sonar) and its token
- In the pipeline run the scan with
withSonarQubeEnv, then wait for the gate with waitForQualityGate
- Create a webhook in SonarQube pointing to
JENKINS_URL/sonarqube-webhook/ so Jenkins is told when analysis finishes
groovy
stage('Sonar analysis') {
steps {
withSonarQubeEnv('sonar') {
sh 'mvn -B sonar:sonar -Dsonar.projectKey=shop-api -Dsonar.qualitygate.wait=false'
}
}
}
stage('Quality gate') {
steps {
timeout(time: 10, unit: 'MINUTES') {
waitForQualityGate abortPipeline: true // fails the build if the gate is not passed
}
}
}
| Sonar term | Meaning |
| Quality Gate | A set of conditions, for example no new bugs, coverage on new code at least 80 percent, duplication under 3 percent |
| New Code | Code changed in a period or since the target branch. The gate focuses here |
| Bugs, Vulnerabilities, Code Smells, Security Hotspots | Issue categories |
| Technical debt | Estimated time to fix the smells |
Security Scans
groovy
stage('Dependency scan') {
steps {
sh 'trivy fs --scanners vuln,secret --severity HIGH,CRITICAL --ignore-unfixed --exit-code 1 --format table .'
}
}
stage('Image scan') {
steps {
sh 'trivy image --severity HIGH,CRITICAL --ignore-unfixed --exit-code 1 registry.example.com/team/shop:${BUILD_NUMBER}'
sh 'trivy image --format cyclonedx --output sbom.json registry.example.com/team/shop:${BUILD_NUMBER}'
archiveArtifacts artifacts: 'sbom.json'
}
}
stage('OWASP Dependency-Check') {
steps {
dependencyCheck additionalArguments: '--scan . --format XML --failOnCVSS 7', odcInstallation: 'dependency-check'
dependencyCheckPublisher pattern: 'dependency-check-report.xml', failedTotalHigh: 1
}
}
Flaky Tests
- A flaky test passes and fails on the same code. It destroys trust in the pipeline
- Track them with the Flaky Test Handler plugin or your test tool's retry reports, fix the root cause (timing, shared data, network) and quarantine tests that cannot be fixed yet
- Retrying the entire pipeline is a bad habit. Retry a single flaky test command in a limited way and report it
Dashboards and Trends
| Where | What you see |
| Job page graphs | Test trend, coverage trend, issue trend over builds |
| Build page | Tabs for Test Result, Coverage, Warnings, Artifacts |
| Pull request checks | Pass or fail and links back to Jenkins (Checks API with the GitHub Checks plugin) |
| SonarQube dashboard | Quality of the code over time |
Practice Tasks
- Publish JUnit results and make a failing test turn the build UNSTABLE and then FAILED
- Add coverage with a threshold on modified lines
- Run a static analysis tool and make a new high-severity issue fail the build
- Connect SonarQube with a webhook and use
waitForQualityGate
- Add a Trivy scan that fails on fixed critical vulnerabilities and archive an SBOM
Conclusion
Quality gates turn CI into a safety net: publish test results, enforce coverage on new code, analyse static issues, use SonarQube's waitForQualityGate and scan dependencies and images with Trivy. Gate on new code, remove flaky tests and show trends so quality only improves.
Quick Summary: gates table; junit + unstable; Coverage plugin gates; recordIssues gates; Sonar + webhook + waitForQualityGate; Trivy/ODC; flaky tests; dashboards.