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

来源:互联网 发布:淘宝买的官换机坏了 编辑:程序博客网 时间:2024/05/22 00:12

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>

0 0
原创粉丝点击