代码测试覆盖率Cobertura使用

本文介绍了在软件测试中如何使用Cobertura工具来测量代码覆盖率,特别是在maven项目中的配置和操作步骤,包括行覆盖率、分支覆盖率等指标的含义,并提到了在多模块项目和IDEA中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

软件测试中,代码覆盖率是一项衡量是否所有代码都被测到的指标,下面以maven项目为例说明Cobertura工具的使用。(当然还有其他的代码覆盖率测试工具,Emma、Gcov、Lcov等,可以按自己的需求选择合适的工具)

1.在maven中添加配置

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>cobertura-maven-plugin</artifactId>
    <version>2.6</version>
    <configuration>
        <formats>
            <format>html</format>
            <format>xml</format>
        </formats>
    </configuration>
</plugin>

2.项目中一些不需要测试的接口定义等可以过滤掉

1> 对类别过滤

在中添加以下配置可以对main方法过滤

 <ignores>
            <!--经过修改的 cobertura, 支持方法级别的过滤 -->
            <ignore>*main*</ignore>
            <!--以上修改指的是过滤项目中所有类中的方法名中含有 main 的方法 -->
 </ignores>
 <IgnoreTrival>true</IgnoreTrival>

2> 对路径过滤

<configuration>
<instrumentation>
    <excludes>
    <!--此处用于指定哪些类会从单元测试的统计范围中被剔除 -->
                <exclude>src/main/java/test/web/controller/*Test.class</exclude>  <exclude>src/main/java/test/web/service/*Test.class</exclude>
    </excludes>
</instrumentation>
</configuration>
    <executions>
          <execution>
                <goals>
                     <goal>clean</goal>
                </goals>
           </execution>
   </executions>

3.运行命令
mvn cobertura:help 查看cobertura插件的帮助
mvn cobertura:clean 清理插件生产的中间及最终报告文件
mvn cobertura:check 检查最后一次标注(instrumentation) 正确与否
mvn cobertura:cobertura 运行cobertura的检查任务并生成报表,报表生成在target/site/cobertura目录下
cobertura:dump-datafile Cobertura 数据文件 dump 指令 , 不常用
mvn cobertura:instrument 标注编译好的 javaclass 文件
4.分析结果指标及含义
1> Line Coverage(行覆盖率)
The percent of lines executed by this test run.
2> Branch Coverage(分支覆盖率)
The percent of branches executed by this test run.
3> Complexity(复杂度)
Average McCabe’s cyclomatic code complexity for all methods. This is basically a count of the number of different code paths in a method (incremented by 1 for each if statement, while loop, etc.)
4> N/A
Line coverage and branch coverage will appear as “Not Applicable” when Cobertura can not find line number information in the .class file. This happens for stub and skeleton classes, interfaces, or when the class was not compiled with “debug=true.”

5.注意细节:
1> 以上分析基于单模块(测试代码和源代码在同一个模块中),如果项目是多模块(测试代码和源代码在不同的模块中)则需要maven+Ant来具体分析,详细配置可以参考链接文档: http://blog.youkuaiyun.com/baynkbtg/article/details/53116683
2> 如果要使用Ant,需要注意build.xml的配置
3> 如果要得到单个测试用例的测试覆盖率,可以使用idea自带的run with coverage

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值