Introduction to Cobertura – 科贝尔图拉简介

最后修改: 2017年 2月 25日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this article, we will demonstrate several aspects of generating code coverage reports using Cobertura.

在这篇文章中,我们将演示使用Cobertura生成代码覆盖率报告的几个方面

Simply put, Cobertura is a reporting tool that calculates test coverage for a codebase – the percentage of branches/lines accessed by unit tests in a Java project.

简单地说,Cobertura是一个计算代码库测试覆盖率的报告工具–在一个Java项目中被单元测试访问的分支/行的百分比。

2. Maven Plugin

2.Maven Plugin

2.1. Maven Configuration

2.1.Maven配置

In order to start calculating code coverage in your Java project, you need to declare the Cobertura Maven plugin in your pom.xml file under the reporting section:

为了在您的Java项目中开始计算代码覆盖率,您需要在pom.xml文件中的报告部分声明Cobertura Maven插件。

<reporting>
    <plugins>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>cobertura-maven-plugin</artifactId>
            <version>2.7</version>
        </plugin>
    </plugins>
</reporting>

You can always check the latest version of the plugin in the Maven central repository.

您可以随时在Maven中央仓库中查看该插件的最新版本。

Once done, go ahead and run Maven specifying cobertura:cobertura as a goal.

完成后,继续运行Maven,指定cobertura:cobertura为目标。

This will create a detailed HTML style report showing code coverage statistics gathered via code instrumentation:

这将创建一个详细的HTML风格的报告,显示通过代码仪表收集的代码覆盖率统计。

cob-e1485730773190

The line coverage metric shows how many statements are executed in the Unit Tests run, while the branch coverage metric focuses on how many branches are covered by those tests.

行覆盖率指标显示在单元测试运行中执行了多少条语句,而分支覆盖率指标则关注这些测试覆盖了多少个分支

For each conditional, you have two branches, so basically, you’ll end up having twice as many branches as conditionals.

对于每个条件,你有两个分支,所以基本上,你最终会有两倍于条件数的分支。

The complexity factor reflects the complexity of the code — it goes up when the number of branches in code increases.

复杂性系数反映了代码的复杂性–当代码中的分支数量增加时,它就会上升。

In theory, the more branches you have, the more tests you need to implement in order to increase the branch coverage score.

理论上,你的分支越多,你需要实现的测试就越多,以提高分支覆盖率的分数。

2.2. Configuring Code Coverage Calculation and Checks

2.2.配置代码覆盖率计算和检查

You can ignore/exclude a specific set of classes from code instrumentation using the ignore and the exclude tags:

你可以使用ignoreexclude标签从代码检测中忽略/排除一组特定的类。

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>cobertura-maven-plugin</artifactId>
    <version>2.7</version>
    <configuration>
        <instrumentation>
            <ignores>
                <ignore>com/baeldung/algorithms/dijkstra/*</ignore>
            </ignores>
            <excludes>
                <exclude>com/baeldung/algorithms/dijkstra/*</exclude>
            </excludes>
        </instrumentation>
    </configuration>
</plugin>

After calculating the code coverage comes the check phase. The check phase ensures that a certain level of code coverage is reached.

计算完代码覆盖率后,就是检查阶段。检查阶段确保代码覆盖率达到一定水平

Here’s a basic example on how to configure the check phase:

下面是一个关于如何配置检查阶段的基本例子。

<configuration>
    <check>
        <haltOnFailure>true</haltOnFailure>
        <branchRate>75</branchRate>
        <lineRate>85</lineRate>
        <totalBranchRate>75</totalBranchRate>
        <totalLineRate>85</totalLineRate>
        <packageLineRate>75</packageLineRate>
        <packageBranchRate>85</packageBranchRate>
        <regexes>
            <regex>
                <pattern>com.baeldung.algorithms.dijkstra.*</pattern>
                <branchRate>60</branchRate>
                <lineRate>50</lineRate>
             </regex>
        </regexes>
    </check>
</configuration>

When using the haltOnFailure flag, Cobertura will cause the build to fail if one of the specified checks fail.

当使用haltOnFailure标志时,如果指定的检查失败,Cobertura将导致构建失败。

The branchRate/lineRate tags specify the minimum acceptable branch/line coverage score required after code instrumentation. These checks can be expanded to the package level using the packageLineRate/packageBranchRate tags.

branchRate/lineRate标签指定了代码检测后所需的最低可接受的分支/线覆盖率分数。这些检查可以通过packageLineRate/packageBranchRate标签扩展到包级别。

It is also possible to declare specific rule checks for classes with names following a specific pattern by using the regex tag. In the example above, we ensure that a specific line/branch coverage score must be reached for classes in the com.baeldung.algorithms.dijkstra package and below.

也可以通过使用regex标签为名字遵循特定模式的类声明特定的规则检查。在上面的例子中,我们确保com.baeldung.algorithms.dijkstra包及以下的类必须达到特定的行/分支覆盖分数。

3. Eclipse Plugin

3.Eclipse插件

3.1. Installation

3.1.安装

Cobertura is also available as an Eclipse plugin called eCobertura. In order to install eCobertura for Eclipse, you need to follow the steps below and have Eclipse version 3.5 or greater installed:

Cobertura也可以作为一个Eclipse插件,叫做eCobertura。为了给Eclipse安装eCobertura,你需要按照下面的步骤,并且安装了3.5或更高版本的Eclipse。

Step 1: From the Eclipse menu, select HelpInstall New Software. Then, at the work with the field, enter http://ecobertura.johoop.de/update/:

第1步:从Eclipse菜单中,选择帮助安装新软件。然后,在 work with字段,输入http://ecobertura.johoop.de/update/

cob3-e1485814235220

Step 2: Select eCobertura Code Coverage, click “next”, and then follow the steps in the installation wizard.

第2步:选择eCobertura代码覆盖率,点击 “下一步”,然后按照安装向导的步骤操作。

Now that eCobertura is installed, restart Eclipse and show the coverage session view under Windows → Show View → Other → Cobertura.

现在eCobertura已经安装,重新启动Eclipse,并在Windows→显示视图→其他→Cobertura下显示覆盖会话视图。

cob3-e1485814235220-1

3.2. Using Eclipse Kepler or Later

3.2.使用Eclipse Kepler或更高版本

For the newer version of Eclipse (Kepler, Luna, etc.), the installation of eCobertura may cause some problems related to JUnit — the newer version of JUnit packaged with Eclipse is not fully compatible with eCobertura‘s dependencies checker:

对于较新版本的Eclipse(Kepler、Luna等),安装eCobertura可能会导致一些与JUnit有关的问题–与Eclipse打包的较新版本的JUnit与eCobertura的依赖检查器不完全兼容:

Cannot complete the install because one or more required items could not be found.
  Software being installed: eCobertura 0.9.8.201007202152 (ecobertura.feature.group
     0.9.8.201007202152)
  Missing requirement: eCobertura UI 0.9.8.201007202152 (ecobertura.ui 
     0.9.8.201007202152) requires 'bundle org.junit4 0.0.0' but it could not be found
  Cannot satisfy dependency:
    From: eCobertura 0.9.8.201007202152 
    (ecobertura.feature.group 0.9.8.201007202152)
    To: ecobertura.ui [0.9.8.201007202152]

As a workaround, you can download an older version JUnit and place it into the Eclipse plugins folder.

作为一种变通方法,你可以下载一个旧版本的JUnit并把它放到Eclipse插件文件夹中。

This can be done by deleting the folder org.junit.*** from %ECLIPSE_HOME%/plugins, and then copying the same folder from an older Eclipse installation that is compatible with eCobertura.

这可以通过从%ECLIPSE_HOME%/plugins中删除org.junit.***文件夹,然后从与eCobertura兼容的旧Eclipse安装中复制相同的文件夹。

Once done, restart your Eclipse IDE and re-install the plugin using the corresponding update site.

完成后,重新启动你的Eclipse IDE,并使用相应的更新站点重新安装该插件

3.3. Code Coverage Reports in Eclipse

3.3.Eclipse中的代码覆盖率报告</strong

In order to calculate code coverage by a Unit Test, right-click your project/test to open the context menu, then choose the option Cover As → JUnit Test.

为了计算单元测试的代码覆盖率,右击你的项目/测试,打开上下文菜单,然后选择Cover As → JUnit Test选项。

Under the Coverage Session view, you can check the line/branch coverage report per class:

覆盖会议视图下,你可以检查每个班级的行/支部覆盖报告。

Sans-titre-e1487178259898

Java 8 users may encounter a common error when calculating code coverage:

Java 8用户在计算代码覆盖率时可能会遇到一个常见错误:

java.lang.VerifyError: Expecting a stackmap frame at branch target ...

In this case, Java is complaining about some methods not having a proper stack map, due to the stricter bytecode verifier introduced in newer versions of Java.

在这种情况下,由于新版本的Java引入了更严格的字节码验证器,Java正在抱怨一些方法没有一个合适的堆栈图。

This issue can be solved by disabling verification in the Java Virtual Machine.

这个问题可以通过在Java虚拟机中禁用验证来解决。

To do so, right-click your project to open the context menu, select Cover As, and then open the Coverage Configurations view. In the arguments tab, add the -noverify flag as a VM argument. Finally, click on the coverage button to launch coverage calculation.

要做到这一点,右键单击您的项目以打开上下文菜单,选择Cover As,然后打开Coverage Configurations视图。在参数选项卡中,添加-noverify标志作为VM参数。最后,点击coverage按钮,启动覆盖率计算。

You can also use the flag -XX:-UseSplitVerifier, but this only works with Java 6 and 7, as the split verifier is no longer supported in Java 8.

你也可以使用标志-XX:-UseSplitVerifier,但这只适用于Java 6和7,因为Java 8中不再支持分割验证器。

4. Conclusion

4.结论

In this article, we have shown briefly how to use Cobertura to calculate code coverage in a Java project. We have also described the steps required to install eCobertura in your Eclipse environment.

在这篇文章中,我们简要介绍了如何使用Cobertura来计算Java项目的代码覆盖率。我们还介绍了在Eclipse环境中安装eCobertura的步骤。

Cobertura is a great yet simple code coverage tool, but not actively maintained, as it is currently outclassed by newer and more powerful tools like JaCoCo.

Cobertura是一个伟大而简单的代码覆盖工具,但没有得到积极的维护,因为它目前被更新和更强大的工具所取代,如JaCoCo

Finally, you can check out the example provided in this article in the GitHub project.

最后,你可以在GitHub项目中查看本文提供的例子。