'Is there a way to get unit coverage percentage (eg from jacoco) on only new code?
My hypothethical scenario is this:
- I have run my junit tests and generated a jacoco file
- my git diff shows I have changed 10 lines of code
Now the intersection of my git diff and the jacoco information is that 7 of the 10 lines of code changed are covered. ie - I have 70% coverage on new code.
But I had to work that out manually.
I'd like an automated way to work out the percentage how many new lines of code are covered.
My question is: Is there a way to get unit coverage percentage (eg from jacoco) on only new code?
(Note I know sonarqube can do this if you run the scanner with analysis.mode=publish
and get interrogate the task result with the JSON API - I'm looking for something lightweight that a developer can run locally.)
Solution 1:[1]
Have a read of this: https://juliangamble.com/blog/2017/09/01/commit-level-coverage-reporting/
Then use this project: https://github.com/juliangamble/commit-level-coverage-report
Solution 2:[2]
There are two plugins:
- Gradle: diff coverage gradle plugin
- Maven: diff coverage maven plugin
Both are built on top of JaCoCo and able to generate JaCoCo like reports.
Also, they able to fail the build if your coverage ratio is less than expected(the ratio colud be configured by the plugins)
Solution 3:[3]
Jacoco + diff-cover
It is work for me. CI Shell script:
export PATH="${jobPath}"/buildbox/Python-3.8.2/bin:$PATH
python --version
python -m pip install -i http://xx.xx.xx.com/artifactory/api/pypi/xx-pypi-public/simple/ --trusted-host xx.xx.xx.com diff_cover==4.0.1
mvn clean test -Dmaven.test.failure.ignore=true
diff-cover "${WORKSPACE}"/xxx-test/target/site/jacoco/jacoco.xml --compare-branch origin/"${target_branch}" --src-roots $(find . -name java -type d | grep 'src/main/java$' | egrep -v "target|test|testkit") --html-report ${WORKSPACE}/xxx-test/target/site/jacoco/index.html
Solution 4:[4]
Another option without additional plugins is to parse html with regex.
build.gradle part for jacoco:
jacocoTestReport {
dependsOn test
reports {
xml.required = true
csv.required = false
// This method requires html report to be generated
html.required = true
}
}
And then you can use sed to parse the report:
sed -nE 's/^.*<td>Total<([^>]+>){4}([^<]*).*$/Missed instructions: \2/p' build/reports/jacoco/test/html/index.html
Which will print you the percentage from this column:
For only second column:
sed -nE 's/^.*<td>Total<([^>]+>){8}([^<]*).*$/Missed branches: \2/p' build/reports/jacoco/test/html/index.html
For both:
sed -nE 's/^.*<td>Total<([^>]+>){4}([^<]*)([^>]+>){4}([^<]*).*$/First: \2; Second: \4/p' build/reports/jacoco/test/html/index.html
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | hawkeye |
Solution 2 | SergiiGnatiuk |
Solution 3 | Languoguang |
Solution 4 | Orachigami |