且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何配置多模块 Maven + Sonar + JaCoCo 以提供合并覆盖率报告?

更新时间:2022-11-02 20:38:13

我和你的情况一样,网上散落的一半答案很烦人,因为似乎很多人都有同样的问题,但没有有人可能会费心解释他们是如何解决这个问题的.

I was in the same situation as you, the half answers scattered throughout the Internet were quite annoying, since it seemed that many people had the same issue, but no one could be bothered to fully explain how they solved it.

声纳文档 参考 一个带有示例的 GitHub 项目很有帮助.我为解决这个问题所做的是将集成测试逻辑应用于常规单元测试(尽管正确的单元测试应该是特定于子模块的,但并非总是如此).

The Sonar docs refer to a GitHub project with examples that are helpful. What I did to solve this was to apply the integration tests logic to regular unit tests (although proper unit tests should be submodule specific, this isn't always the case).

在父 pom.xml 中,添加这些属性:

In the parent pom.xml, add these properties:

<properties>
    <!-- Sonar -->
    <sonar.java.coveragePlugin>jacoco</sonar.java.coveragePlugin>
    <sonar.dynamicAnalysis>reuseReports</sonar.dynamicAnalysis>
    <sonar.jacoco.reportPath>${project.basedir}/../target/jacoco.exec</sonar.jacoco.reportPath>
    <sonar.language>java</sonar.language>
</properties>

这将使 Sonar 为同一位置(父项目中的目标文件夹)中的所有子模块获取单元测试报告.它还告诉 Sonar 重​​用手动运行的报告,而不是自己滚动.我们只需要将 jacoco-maven-plugin 放在父 pom 中的 build/plugins 中,即可为所有子模块运行:

This will make Sonar pick up unit testing reports for all submodules in the same place (a target folder in the parent project). It also tells Sonar to reuse reports ran manually instead of rolling its own. We just need to make jacoco-maven-plugin run for all submodules by placing this in the parent pom, inside build/plugins:

<plugin>
    <groupId>org.jacoco</groupId>
    <artifactId>jacoco-maven-plugin</artifactId>
    <version>0.6.0.201210061924</version>
    <configuration>
        <destFile>${sonar.jacoco.reportPath}</destFile>
        <append>true</append>
    </configuration>
    <executions>
        <execution>
            <id>agent</id>
            <goals>
                <goal>prepare-agent</goal>
            </goals>
        </execution>
    </executions>
</plugin>

destFile 将报告文件放在 Sonar 将查找它的位置,append 使其附加到文件而不是覆盖它.这会将所有子模块的所有 JaCoCo 报告合并到同一个文件中.

destFile places the report file in the place where Sonar will look for it and append makes it append to the file rather than overwriting it. This will combine all JaCoCo reports for all submodules in the same file.

Sonar 将为每个子模块查看该文件,因为这是我们在上面指出的,为我们提供 Sonar 中多模块文件的组合单元测试结果.

Sonar will look at that file for each submodule, since that's what we pointed him at above, giving us combined unit testing results for multi module files in Sonar.