Test Reports, Code Coverage and Quality Gates: JUnit, JaCoCo, Warnings, SonarQube and Trivy

CI CD Pipelines with Jenkins 40 min min read Updated: Nov 17, 2026 Intermediate
Test Reports, Code Coverage and Quality Gates: JUnit, JaCoCo, Warnings, SonarQube and Trivy
Intermediate Topic 2 of 3

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.

CheckToolTypical rule
Unit testsJUnit, pytest, Jest, xUnitAll pass
CoverageJaCoCo, Cobertura, Coverage pluginAt least 80 percent on new code
Static analysisCheckstyle, SpotBugs, ESLint, Ruff, SonarQubeNo new critical issues
Dependency vulnerabilitiesOWASP Dependency-Check, Trivy, npm auditNo fixed critical or high
Container image scanTrivy, Grype, Docker ScoutNo fixed critical or high
Secrets scanGitleaks, TrivyNone found
License checkLicense Finder, FOSSANo 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] ] )
BaselineMeaning
PROJECTCoverage of the whole project
MODIFIED_FILES, MODIFIED_LINESOnly the changed files or lines (needs a reference build)
PROJECT_DELTAChange 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

  1. Run SonarQube (or SonarCloud) and create a project token; store it as secret text sonar-token
  2. Install the SonarQube Scanner plugin and in *Manage Jenkins, System* add the server (name sonar) and its token
  3. In the pipeline run the scan with withSonarQubeEnv, then wait for the gate with waitForQualityGate
  4. 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 termMeaning
Quality GateA set of conditions, for example no new bugs, coverage on new code at least 80 percent, duplication under 3 percent
New CodeCode changed in a period or since the target branch. The gate focuses here
Bugs, Vulnerabilities, Code Smells, Security HotspotsIssue categories
Technical debtEstimated 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

WhereWhat you see
Job page graphsTest trend, coverage trend, issue trend over builds
Build pageTabs for Test Result, Coverage, Warnings, Artifacts
Pull request checksPass or fail and links back to Jenkins (Checks API with the GitHub Checks plugin)
SonarQube dashboardQuality of the code over time

Practice Tasks

  1. Publish JUnit results and make a failing test turn the build UNSTABLE and then FAILED
  2. Add coverage with a threshold on modified lines
  3. Run a static analysis tool and make a new high-severity issue fail the build
  4. Connect SonarQube with a webhook and use waitForQualityGate
  5. 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.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators