软件测试中,代码覆盖率是一项衡量是否所有代码都被测到的指标,下面以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