按类级别强制实施最低总JUnit覆盖率?

时间:2017-02-08 09:41:30

标签: java maven junit maven-surefire-plugin maven-enforcer-plugin

目前,我在模块级别强制实施最低JUnit总覆盖率。因此,如果总线路覆盖率低于某个值(在我的情况下为80%),则构建失败。为此,我使用了maven-surefire-plugin和maven-enforcer-plugin,JUnit和JMockit。 pom文件部分看起来像这样。

<build>
<plugins>
....
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.18.1</version>
    <dependencies>
        <dependency>
            <groupId>org.apache.maven.surefire</groupId>
            <artifactId>surefire-junit4</artifactId>
            <version>2.18.1</version>
        </dependency>
    </dependencies>
    <configuration>
        <systemPropertyVariables>
            <coverage-outputDir>${basedir}/target/coverageReport</coverage-outputDir>
            <coverage-output>html,merge</coverage-output>               
            <coverage-check>80</coverage-check>
        </systemPropertyVariables>
    </configuration>
</plugin>
<plugin>
    <artifactId>maven-enforcer-plugin</artifactId>
    <executions>
        <execution>
            <id>coverage.check</id>
            <goals>
                <goal>enforce</goal>
            </goals>
            <phase>test</phase>
            <configuration>
                <rules>
                    <requireFilesDontExist>
                        <files>
                            <file>coverage.check.failed</file>
                        </files>
                    </requireFilesDontExist>
                </rules>
            </configuration>
        </execution>
    </executions>
</plugin>
....
</build>
<dependencies>
    ....
        <dependency>
            <groupId>org.jmockit</groupId>
            <artifactId>jmockit</artifactId>
            <version>1.17</version>
        </dependency>
        <dependency>
            <groupId>org.jmockit</groupId>
            <artifactId>jmockit-coverage</artifactId>
            <version>1.17</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
        </dependency>
    ....    
  </dependencies>   

我的问题是,有些课程的覆盖率可能会低于80%,只要总覆盖率不低于80%,构建仍然会通过。

那么,我有什么方法可以在班级强制执行我的报道吗?

1 个答案:

答案 0 :(得分:2)

给你一个自以为是的答案:不要这样做。不要因错过的覆盖率而使你的构建失败!

以下是支持这一点的理由:您正尝试使用技术手段解决社交问题。

你真正的问题是:你想要达到一定的代码质量,并且你认为你可以通过在他们不遵守时惩罚他们来实现这一目标。那不会真的奏效。人们迟早会开始绕过这个想法。他们会寻找快速的方法来制作#34;快乐;通过要求合理的代码覆盖率忽略了提高代码质量的想法。或者一些经理来找你,指出新的功能/修复现在更重要的是当前的覆盖目标。 那又怎样?暂时禁用检查?允许更低的数字?

当然,测量单元测试的覆盖范围是好事。您应该经常这样做,并使您的开发人员可以轻松访问此信息(例如,将其放在某个仪表板上)。要求您的DEV团队实现某些目标也是公平的。但强迫某些覆盖率下降到每个人的喉咙......都无法解决。

(好吧:如果您在高级环境中工作,每个开发人员不仅接受您的想法,而且完全支持您;那么事情可能会有所不同。但是如果你将生活在这样的环境中,那么高覆盖率本身就会出现;而不是强制执行它。)