Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Sample projects are available on github that can be browsed or downloaded: projects/code-coverage/combined ut-it/maven/combined-ut-it-multimodule-maven-jacoco

Note that this project structure is not compatible with the below feature: mapping of unit tests and covered code.

Mapping of Unit Tests and Covered Code

Since Sonar 3.5, it is possible to display the mapping of unit tests and covered code. The objective is to answer the following questions:

  • Which files are covered by a given unit test?
  • How many lines of code are covered by a given unit test?
  • Which lines are covered by a given unit test?
  • Which tests do cover a given line of code?
See Resource Viewer on Unit Tests for more details.

This use case can only be achieved with Maven and JaCoCo for now.

A sample project is available on github that can be browsed or downloaded: projects/code-coverage/ut/maven/ut-maven-jacoco-runTests. What is necessary to get this mapping is contained between 'BEGIN/END: Specific to mapping unit tests and covered code' tags in the pom file. Note that you have to run the analysis with the 'coverage-per-test' profile. Read the README file for more information.

Reusing Existing Reports

Every analyzer supports this reusing reports mode.

...

Code Block
languagehtml/xml
sonar.surefire.reportsPath=[baseDir]/myReports/myExecutionReports

Code Coverage Report 

Tell Sonar where your code coverage report is: absolute or relative path to the report file for JaCoCo or Cobertura or Clover, directory path for Emma.

First, tell Sonar which code coverage engine has been used to generate the reports: jacoco or cobertura or emma or clover.

Code Block
languagehtml/xml
<sonar.java.coveragePlugin>jacoco or cobertura or emma or clover</sonar.java.coveragePlugin>
 
Prior to Sonar 3.4, the property was sonar.core.codeCoveragePlugin.

Then, tell Sonar where to get the code coverage reports:

With Maven in your pom file:

Code Block
languagehtml/xml
<sonar.jacoco.reportPath>[baseDir]/myReports/myCodeCoverageReport</sonar.jacoco.reportPath>

...

Code Block
languagehtml/xml
sonar.jacoco.reportPath=[baseDir]/myReports/myCodeCoverageReport

Depending on the code coverage tool you used to generate your report, replace jacoco by emmacobertura or clover in the property name. 

Blog

See also the Manage Code Coverage by Unit Tests with Sonar blog post.

FAQ

0% code coverage reported whereas unit tests are correctly executed

This problem occurs while using the Maven Cobertura Plugin and a special configuration of the Maven Surefire Plugin preventing unit tests to be forked. This problem can be solved by removing the line "<forkMode>never</forkMode>" in the Maven configuration file (see SONAR-1445 and MCOBERTURA-70).