背景:项目开发中由于研发任务紧,开发人员往往不写单元测试或者随意编写几个测试方法,对于技术经理来说需要通过技术手段来强制要求开发人员编写单元测试,并且要求达到指定的测试覆盖率标准才能达到提测标准等要求。
项目以采用Maven 工程为例:
pom.xml 配置依赖和插件配置
<dependencies>
<!-- 配置依赖 -->
<dependency>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.7.8</version>
<scope>test</scope>
</dependency>
</dependencies>
<!-- 配置maven插件 -->
<build>
<plugins>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.7.8</version>
<executions>
<execution>
<id>prepare-agent</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>check</id>
<goals>
<goal>check</goal>
</goals>
</execution>
<execution>
<id>report</id>
<phase>prepare-package</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
</executions>
<configuration>
<!-- 单元测试代码覆盖率插件 -->
<rules>
<rule implementation="org.jacoco.maven.RuleConfiguration">
<element>BUNDLE</element>
<limits>
<!-- 指定方法覆盖到应该达到80% -->
<limit implementation="org.jacoco.report.check.Limit">
<counter>METHOD</counter>
<value>COVEREDRATIO</value>
<minimum>0.8</minimum>
</limit>
<!-- 指定指令覆盖到应该达到80% -->
<limit implementation="org.jacoco.report.check.Limit">
<counter>INSTRUCTION</counter>
<value>COVEREDRATIO</value>
<minimum>0.8</minimum>
</limit>
<!-- 指定行覆盖率应该达到80% -->
<limit implementation="org.jacoco.report.check.Limit">
<counter>LINE</counter>
<value>COVEREDRATIO</value>
<minimum>0.8</minimum>
</limit>
<!-- 应该设置为:0 (类覆盖率100%,不应该缺失任何类) -->
<limit implementation="org.jacoco.report.check.Limit">
<counter>CLASS</counter>
<value>MISSEDCOUNT</value>
<maximum>0</maximum>
</limit>
</limits>
</rule>
</rules>
</configuration>
</plugin>
</plugins>
</build>
运行单元测试并统计代码覆盖率命令:
mvn clean compile jacoco:report test install
结果由于单元测试覆盖率不满足以上要求规则,出现一下错误。
[INFO] --- jacoco-maven-plugin:0.7.8:check (check) @ lyh-api ---
[INFO] Loading execution data file /Users/kevin/java_home/lyh-api/target/jacoco.exec
[INFO] Analyzed bundle 'lyh-api' with 12 classes
[WARNING] Rule violated for bundle lyh-api: methods covered ratio is 0.3, but expected minimum is 0.8
[WARNING] Rule violated for bundle lyh-api: instructions covered ratio is 0.2, but expected minimum is 0.8
[WARNING] Rule violated for bundle lyh-api: lines covered ratio is 0.3, but expected minimum is 0.8
[WARNING] Rule violated for bundle lyh-api: classes missed count is 4, but expected maximum is 0
此时要求开发人员技术补全单元测试,这里由于演示使用,可以将要求标准降低,使其满足要求并生成测试覆盖率报告
重新执行命令:mvn clean compile jacoco:report test install
不出意外测试成功,就可以在工程target/site/jacoco/index.html 查看测试报告