How to Publish Code Coverage Reports in Jenkins
To publish code coverage in Jenkins, use a coverage plugin like
JaCoCo or Cobertura. Configure your Jenkins job to run tests and generate coverage reports, then add the plugin's post-build action to publish the coverage results on the Jenkins dashboard.Syntax
In Jenkins pipeline, publishing code coverage typically involves these steps:
- Run tests with coverage enabled to generate a report file (e.g.,
jacoco.xmlorcoverage.xml). - Use the coverage plugin step to publish the report, for example
jacoco()orcobertura(). - Configure the plugin to point to the report file location.
Example Jenkins pipeline syntax for JaCoCo coverage publishing:
groovy
pipeline {
agent any
stages {
stage('Build and Test') {
steps {
// Run tests with coverage
sh './gradlew clean test jacocoTestReport'
}
}
}
post {
always {
jacoco execPattern: '**/build/jacoco/test.exec', classPattern: '**/classes', sourcePattern: '**/src/main/java', exclusionPattern: ''
}
}
}Example
This example shows a Jenkins pipeline that runs tests with JaCoCo coverage and publishes the coverage report on Jenkins UI.
groovy
pipeline {
agent any
stages {
stage('Build') {
steps {
sh './gradlew clean build'
}
}
stage('Test with Coverage') {
steps {
sh './gradlew test jacocoTestReport'
}
}
}
post {
always {
jacoco execPattern: '**/build/jacoco/test.exec', classPattern: '**/classes', sourcePattern: '**/src/main/java'
}
}
}Output
Jenkins job runs tests, generates JaCoCo coverage report, and displays coverage summary in the job dashboard under 'Coverage Report'.
Common Pitfalls
- Incorrect report path: The coverage plugin must point to the exact location of the coverage report file; wrong paths cause no data shown.
- Missing coverage generation: Ensure your build tool is configured to generate coverage reports before publishing.
- Plugin not installed: The JaCoCo or Cobertura plugin must be installed in Jenkins.
- Pipeline syntax errors: Use the correct plugin step syntax in your Jenkinsfile.
groovy
/* Wrong way: Missing report path */ jacoco() /* Right way: Specify report paths */ jacoco execPattern: '**/build/jacoco/test.exec', classPattern: '**/classes', sourcePattern: '**/src/main/java'
Quick Reference
| Step | Description | Example |
|---|---|---|
| Generate coverage report | Run tests with coverage enabled | ./gradlew test jacocoTestReport |
| Publish coverage | Use Jenkins plugin step to publish report | jacoco execPattern: '**/build/jacoco/test.exec' |
| Verify | Check coverage report in Jenkins job dashboard | View 'Coverage Report' section |
Key Takeaways
Install and configure a coverage plugin like JaCoCo or Cobertura in Jenkins.
Run tests with coverage enabled to generate the coverage report file.
Use the plugin's post-build step or pipeline step to publish the coverage report.
Ensure the report file paths in the plugin configuration match your build output.
Check the Jenkins job dashboard to view the published coverage results.