促销服务使用集成测试统计覆盖率的实践

背景

promotion-compose是多模块结构的maven工程,其中配置文件信息以及单元测试都web层,这在考拉中应该是很普遍的。在promotion-compose工程是一个相对较新的工程,在该工程中是比较注重单元测试覆盖的,单元测试用例比较多;但是在sonar平台上统计到的测试覆盖率只有13%,也就是只统计到了300多行代码。这是什么鬼?通过覆盖和未覆盖到代码可以发现这个代码行数只统计到了web层模块,根本没有统计到所有模块。这明显是不合理的覆盖率统计,为了更准确反映单元测试覆盖率,咨询了相关测试开发同学居然要求在每个模块都要写测试用例,这个是难以忍受的方案。通过查找相关资料发现对单元测试覆盖率的配置进行调整是可以实现目标的。

实现

查找了Jacoco官方文档描述如下:

jacoco:report

Note:This goal should be used as a Maven report.

Full name:

org.jacoco:jacoco-maven-plugin:0.7.10-SNAPSHOT:report

Description:

Creates a code coverage report for tests of a single project in multiple formats (HTML, XML, and CSV).

原来该配置只执行了单元测试,而单元测试只能统计到当前模块!有没有其他方案呢?那就是使用集成测试,具体的配置如下:

总POM的配置修改如下:

<plugin>
  <groupId>org.jacoco</groupId>
  <artifactId>jacoco-maven-plugin</artifactId>
  <configuration>
    <append>true</append>
  </configuration>
  <executions>
     <execution>
    <id>agent-for-ut</id>
    <goals>
       <goal>prepare-agent</goal>
        </goals>
     </execution>
     <execution>
       <id>agent-for-it</id>
       <goals>
    <goal>prepare-agent-integration</goal>
       </goals>
     </execution>
    <execution>
       <id>jacoco-site</id>
       <goals>
         <goal>report</goal>
        </goals>
    </execution>
      </executions>
   </plugin>
<pluginManagement>
    <plugins>
    <plugin>
       <groupId>org.jacoco</groupId>
       <artifactId>jacoco-maven-plugin</artifactId>
           <version>0.7.9</version>
        </plugin>
           </plugins>
</pluginManagement>

web层POM配置

<plugin>
   <groupId>org.apache.maven.plugins</groupId>
   <artifactId>maven-antrun-plugin</artifactId>
   <version>1.7</version>
   <executions>
     <execution>
     <phase>install</phase>
     <configuration>
       <tasks>
            <copy failonerror="false" file="target/jacoco-it.exec"  todir="../kaola-promotion-compose-provider/target" />
                        <copy failonerror="false" file="target/jacoco-it.exec"  todir="../kaola-promotion-compose-api/target" />
                        <copy failonerror="false" file="target/jacoco-it.exec"  todir="../kaola-promotion-generic-provider/target" />
                        <copy failonerror="false" file="target/jacoco-it.exec"  todir="../kaola-promotion-generic-api/target" />
                        <copy failonerror="false" file="target/jacoco-it.exec"  todir="../kaola-promotion-dict/target" />
    </tasks>
      </configuration>
      <goals>
    <goal>run</goal>
      </goals>
     </execution>
    </executions>
</plugin>
<plugin>
  <groupId>org.jacoco</groupId>
  <artifactId>jacoco-maven-plugin</artifactId>
  <configuration>
     <destFile>target/jacoco-it.exec</destFile>
  </configuration>
</plugin>

sonar 上关于单元测试的执行命令需要修改为:

mvn clean install

效果



goods-front和promotion-compose覆盖情况对比

在没有增加测试用例的情况下测试覆盖率有了明显提升,同时对于测试覆盖情况也有了一个比较准确的反馈。希望对各位小伙伴有帮助

参考资料

本文来自网易实践者社区,经作者张伟授权发布。