您的位置:首页 > 编程语言

maven中实现代码单元测试覆盖率统计

2014-11-26 10:33 495 查看
1.首先需要对统计模块的POM.XML增加如下字段:



<build>

<plugins>

<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>

</plugins>

</reporting>

或用<reporting>标签,如下:

<reporting>

<plugins>

<plugin>

<groupId>org.codehaus.mojo</groupId>

<artifactId>cobertura-maven-plugin</artifactId>

<version>2.6</version>

</plugin>

</plugins>

</reporting>

区别:在reporting节点中加入则在mvn
site中执行,如果在build节点中加入,则在build的时候自动运行检查。
注意:如果是多模块的maven项目,需要在每个想统计模块的pom.xml中进行配置,这样会将各模块的报告进行汇集。

2.执行下面的cobertura命令

[plain] view
plaincopy

mvn cobertura:help 查看cobertura插件的帮助

mvn cobertura:clean清空cobertura插件运行结果

mvn cobertura:check运行cobertura的检查任务

mvn cobertura:cobertura 运行cobertura的检查任务并生成报表,报表生成在target/site/cobertura目录下

cobertura:dump-datafile Cobertura Datafile Dump Mojo

mvn cobertura:instrument Instrument the compiled classes

另,有的项目一些借口定义,常量定义和异常定义这些是不需要单元测试的,还有一些不重要的,我们可以进行过滤

按类的类别进行过滤
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>cobertura-maven-plugin</artifactId>
<version>2.5.2</version>
<configuration>
<ignores>
<!--经过修改的 cobertura, 支持方法级别的过滤 -->
<ignore>*main*</ignore>
<!--以上修改指的是过滤项目中所有类中的方法名中含有 main 的方法 -->
</ignores>
<IgnoreTrival>true</IgnoreTrival>
</configuration>
</plugin>

或对路径过滤:
<configuration>

 <instrumentation> 

 <excludes> 

 <!--此处用于指定哪些类会从单元测试的统计范围中被剔除 -->

 <exclude>exs/res/process/egencia/Mock*.class</exclude>

 <exclude>exs/res/process/test/**/*Test.class</exclude> </excludes>

 </instrumentation> 

 </configuration> 

 <executions> 

 <execution>

 <goals> 

<goal>clean</goal> 

 </goals> 

  </execution>

</executions>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: