Maven和代码度量:检查每个类是否存在测试用例

And*_*rea 6 java checkstyle pmd code-metrics maven

是否有可以在Maven中使用的东西来自动进行这种检查?我看到checkstyle和PMD,但我没有找到这个功能.

基本上我觉得如果有一个类A而且没有一个类,那么构建就会失败ATestCase.我知道,这不是一个严格的检查,只需创建一个类就可以轻松绕过,但此刻就足够了.

Jea*_*evy 3

你在寻找什么

正如 Jens Piegsa 指出的那样,您正在寻找的是一个可以显示测试覆盖率的工具,换句话说,就是您的测试使用的代码的百分比。

它允许您以一种比(至少按类测试)更可靠的方式查看您的代码经过了多少测试。

您可以使用 Cobertura,它很好地集成在 Maven 中:http ://mojo.codehaus.org/cobertura-maven-plugin/

实现这一目标的方法

POM配置

只需将此代码片段放入您的 pom.xml 中即可

<project>
  ...  
  <reporting>
    <plugins>
      ...
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>cobertura-maven-plugin</artifactId>
        <version>2.6</version>
      </plugin>
    </plugins>
  </reporting>
</project>
Run Code Online (Sandbox Code Playgroud)

跑步覆盖范围

并运行

 mvn cobertura:cobertura
Run Code Online (Sandbox Code Playgroud)

或者运行报告阶段(与站点生成绑定)

 mvn site:site
Run Code Online (Sandbox Code Playgroud)

添加质量阈值

如果您想让低覆盖率构建失效,您甚至可以添加失败阈值

    <plugin>
         [...]
         <configuration>
            <check>
                <!-- Fail if code coverage does not respects the goals  -->
                <haltOnFailure>true</haltOnFailure>
                <!-- Per-class thresholds -->
                <lineRate>80</lineRate>
                <!-- Per-branch thresholds (in a if verify that if and else are covered-->
                <branchRate>80</branchRate>
                <!-- Project-wide thresholds -->
                <totalLineRate>90</totalLineRate>
                <totalBranchRate>90</totalBranchRate>
            </check>
        </configuration>
    </plugin>
Run Code Online (Sandbox Code Playgroud)