如果JUnit覆盖率低于特定阈值,如何使Maven构建失败

我从声纳休息API获取单元测试覆盖率百分比指标。

如果构建低于定义值,如何使构建失败?

回答:

JaCoCo 提供该功能。

JaCoCo与 配置规则

定义JaCoCo插件使用配置规则COVEREDRATIOLINEBRANCH

<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)。

指令示例-整体指令覆盖率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>

失败消息

如果覆盖范围不符合预期,它将失败并显示以下消息:

[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 …)。您也许也可以使用正则表达式。


资料来源:

  • http://choudhury.com/blog/2014/02/25/enforcing-minimum-code-coverage
  • http://www.eclemma.org/jacoco/trunk/doc/maven.html
  • http://www.eclemma.org/jacoco/trunk/doc/check-mojo.html

以上是 如果JUnit覆盖率低于特定阈值,如何使Maven构建失败 的全部内容, 来源链接: utcz.com/qa/397316.html

回到顶部