Analyzing code coverage with the Maven Cobertura plugin

Cobertura is another popular Java tool that calculates the percentage of code accessed by tests. It is based on jcoverage. There are many ways to use Cobertura, including standalone, through Ant script, and Maven. Let us use the Maven Cobertura plugin.

How to do it...

Use the following steps to analyze the code coverage with the Maven Cobertura plugin:

  1. Open a Maven project that has unit tests (for instance, project-with-tests).
  2. Run the following command:
    mvn cobertura:cobertura
    
  3. Observe the following output:
    [INFO] <<< cobertura-maven-plugin:2.6:cobertura (default-cli) < [cobertura]test@ project-with-tests <<<
    [INFO]
    [INFO] --- cobertura-maven-plugin:2.6:cobertura (default-cli) @ project-with-tests ---
    [INFO] Cobertura 2.0.3 - GNU GPL License (NO WARRANTY) - See COPYRIGHT file
    Report time: 165ms
    [ERROR] Nov 15, 2014 5:06:25 PM
    net.sourceforge.cobertura.coveragedata.CoverageDataFileHandler loadCoverageData
    INFO: Cobertura: Loaded information on 1 classes.
    
  4. See the report generated:
    How to do it...

How it works...

JaCoCo instruments the code online when the tests are running and hence,it needs to have the agent running. On the other hand, Cobertura instruments the bytecode during compilation offline. The cobertura goal of the Cobertura Maven plugin instruments the project, runs the tests, and generates the report.

There are separate goals to instrument and check results, if required.

There's more...

What if we want to fail the build if the code coverage is below a threshold level? We can set up Cobertura to do this:

  1. Add the following to the pom file:
         <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>cobertura-maven-plugin</artifactId>
            <version>2.6</version>
            <configuration>
              <check>
                <branchRate>85</branchRate>
                <lineRate>85</lineRate>
                <haltOnFailure>true</haltOnFailure>
              </check>
            </configuration>
            <executions>
              <execution>
                <goals>
                  <goal>check</goal>
                </goals>
              </execution>
            </executions>
          </plugin>
  2. Run the following command:
    mvn cobertura:check
    
  3. Observe the output as shown in the following screenshot:
    There's more...

The build has failed because, in the pom file, we specified that the build should be halted if the coverage is less than 85%.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.38.121