为了账号安全,请及时绑定邮箱和手机立即绑定

如何在maven 中进行单元测试测试代码覆盖率?

如何在maven 中进行单元测试测试代码覆盖率?

狐的传说 2018-11-21 23:19:38
如何在maven 中进行单元测试测试代码覆盖率
查看完整描述

1 回答

?
杨__羊羊

TA贡献1943条经验 获得超7个赞

1.首先需要对统计模块的POM.XML增加如下字段:




  1. <build>  

  2.         <plugins>  

  3.             <plugin>  

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

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

  6.                 <version>2.6</version>

  7.                <configuration>

  8.                    <formats>

  9.                       <format>html</format>

  10.                       <format>xml</format>

  11.                    </formats>

  12.                 </configuration>  

  13.             </plugin>  

  14.         </plugins>  

  15.     </reporting>



或用<reporting>标签,如下:


  1. <reporting>  

  2.         <plugins>  

  3.             <plugin>  

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

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

  6.                 <version>2.6</version>  

  7.             </plugin>  

  8.         </plugins>  

  9.     </reporting>  


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



[plain] view plaincopy

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

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

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

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

  5. cobertura:dump-datafile     Cobertura Datafile Dump Mojo  

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



查看完整回答
反对 回复 2018-12-12
  • 1 回答
  • 0 关注
  • 1336 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信