有许多代码覆盖率工具已经达到了生命周期的终点,这使得查找工具有点困难。我想知道是否有人有使用过可以从 Java Maven 项目的测试角度显示代码覆盖率的工具的经验。
类似这样的事情:
Test: myTest
Coverage:covers 30 % of source code.
并以 XML 或 JSON 格式导出此结果。
以 Jacoco 为例。来自 @cesarsotovalero 撰写的信息
运行一种测试方法
mvn clean verify -Dtest=yourTestClass#yourTestMethod
或者运行一个测试类
mvn clean verify -Dtest=yourTestClass
或者运行整个测试套件
mvn clean test
测试的名称现在将存在于 \target\surefire-reports\TEST-yourTest.xml
覆盖结果将位于 \target\site\jacoco\jacoco.xml
现在您可以读取测试名称并将其映射到测试结果。在 \target\site\jacoco\jacoco.xml
的 XML 底部有一个摘要:
<counter covered="10" missed="19" type="INSTRUCTION"/>
<counter covered="3" missed="5" type="LINE"/>
<counter covered="3" missed="2" type="COMPLEXITY"/>
<counter covered="3" missed="2" type="METHOD"/>
<counter covered="2" missed="0" type="CLASS"/>
\target\surefire-reports\TEST-yourTest.xml
中测试的测试覆盖率是
3/(3+5) = 37.5 %
最佳答案
JaCoCo完全符合您的要求。将其作为插件添加到 pom.xml
您的 Maven 项目文件如下:
<build>
<plugins>
<!-- JaCoCo plugin-->
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.5</version>
<executions>
<execution>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>report</id>
<phase>prepare-package</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
要获取单个测试的覆盖率百分比,请运行:
mvn clean verify -Dtest=myTestClass#myTestMethod
覆盖率结果将导出至./target/site/jacoco/jacoco.xml
。此外,将在 ./target/site/jacoco/index.html
生成一个漂亮的 HTML 报告。 .
您可以解析jacoco.xml
文件来获取测试类的测试覆盖率:(lines missing + lines covered) / lines covered
.
关于java - 当前哪些 Java 代码覆盖率工具可以从测试的角度显示覆盖率?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61190404/