我从声纳休息API获取单元测试覆盖率百分比指标。
如果构建低于定义值,如何使构建失败?
JaCoCo 提供该功能。
JaCoCo
定义JaCoCo插件使用配置规则COVEREDRATIO的LINE和BRANCH:
COVEREDRATIO
LINE
BRANCH
<plugin> <groupId>org.jacoco</groupId> <artifactId>jacoco-maven-plugin</artifactId> <version>0.7.7.201606060606</version> <executions> <execution> <id>default-prepare-agent</id> <goals> <goal>prepare-agent</goal> </goals> </execution> <execution> <id>check</id> <goals> <goal>check</goal> </goals> <configuration> <rules> <rule> <element>CLASS</element> <limits> <limit> <counter>LINE</counter> <value>COVEREDRATIO</value> <minimum>0.80</minimum> </limit> <limit> <counter>BRANCH</counter> <value>COVEREDRATIO</value> <minimum>0.80</minimum> </limit> </limits> <excludes> <exclude>com.xyz.ClassToExclude</exclude> </excludes> </rule> </rules> </configuration> </execution> </executions> </plugin>
支持的counter选项有:
counter
我相信INSTRUCTION您可以进行一般检查(例如,验证整个项目的覆盖率至少为0.80)。
INSTRUCTION
指令示例-整体指令覆盖率80%
本示例要求整个指令的覆盖率为80%,并且不得错过任何课程: <rules> <rule implementation="org.jacoco.maven.RuleConfiguration"> <element>BUNDLE</element> <limits> <limit implementation="org.jacoco.report.check.Limit"> <counter>INSTRUCTION</counter> <value>COVEREDRATIO</value> <minimum>0.80</minimum> </limit> <limit implementation="org.jacoco.report.check.Limit"> <counter>CLASS</counter> <value>MISSEDCOUNT</value> <maximum>0</maximum> </limit> </limits> </rule> </rules>
本示例要求整个指令的覆盖率为80%,并且不得错过任何课程:
<rules> <rule implementation="org.jacoco.maven.RuleConfiguration"> <element>BUNDLE</element> <limits> <limit implementation="org.jacoco.report.check.Limit"> <counter>INSTRUCTION</counter> <value>COVEREDRATIO</value> <minimum>0.80</minimum> </limit> <limit implementation="org.jacoco.report.check.Limit"> <counter>CLASS</counter> <value>MISSEDCOUNT</value> <maximum>0</maximum> </limit> </limits> </rule> </rules>
如果覆盖范围不符合预期,它将失败并显示以下消息:
[WARNING] Rule violated for class com.sampleapp.SpringConfiguration: lines covered ratio is 0.00, but expected minimum is 0.80 [WARNING] Rule violated for class com.sampleapp.Launcher: lines covered ratio is 0.33, but expected minimum is 0.80 [INFO] ------------------------------------------------------------------------ [INFO] BUILD FAILURE [INFO] ------------------------------------------------------------------------
在上面的示例中,我设置了<exclude>com.xyz.ClassToExclude</exclude>。我认为您会发现需要添加许多排除项。项目通常包含许多无法测试/测试的类(Spring Configuration,Java Bean …)。您也许也可以使用正则表达式。
<exclude>com.xyz.ClassToExclude</exclude>