我从 sonar rest api 获取单元测试覆盖率指标.
I'm getting the Unit test coverage percentage metric from sonar rest api.
如果构建低于定义的值,我怎么会失败?
How can I fail the build if it falls below a defined value?
JaCoCo
提供了该功能.
使用LINE
和BRANCH
的配置规则COVEREDRATIO
定义JaCoCo插件:
Define JaCoCo plugin using configuration rules COVEREDRATIO
forLINE
and 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
选项有:
我相信 INSTRUCTION
将允许您进行一般检查(例如,验证整个项目的覆盖率至少为 0.80).
I believe INSTRUCTION
would allow you to make a general check (verify that the whole project has at least 0.80 of coverage for instance).
INSTRUCTION 示例 - 80% 的总体指令覆盖率
此示例需要 80% 的整体指令覆盖率,并且没有必须错过课程:
This example requires an overall instruction coverage of 80% and no class must be missed:
<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>
如果覆盖范围不符合预期,则会失败并显示以下消息:
If the coverage isn't as expected, it fails with the following message:
[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 配置、Java bean ...).您也可以使用正则表达式.
In the example above, I set <exclude>com.xyz.ClassToExclude</exclude>
. I think you'll find you need to add many exclusions. Projects usually contain many classes which aren't testable/tested (Spring Configuration, Java beans...). You may be able to use regular expression too.
这篇关于如果 JUnit 覆盖率低于某个阈值,如何使 Maven 构建失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!