如何在 SonarQube 中获得每次测试的覆盖率?

How to get coverage per test in SonarQube?

我很难以某种方式设置我的项目,因此 SonarQube 会报告每个测试的测试覆盖率。

在使用 Sonar Scanner 进行分析时,我只看到了

No information about coverage per test.

读取 JaCoCo 执行数据后。

这个工作的要求是什么?显示每个测试的覆盖率的最小示例看起来如何。

我当前的环境是这样的:

我的测试项目是这样的:

Workspace
+- EclipseProject
|  +- bin
|  |  +- foo
|  |  |  +- FooClass.class
|  |  +- tests
|  |     +- FooTestClass.class
|  +- src
|     +- foo
|     |  +- FooClass.java // Class with getter/setter for a private 
|     |                   // instance variable.
|     +- tests
|        +- FooTestClass.java // Two JUnit 4 tests: test1 checks getter,
|                             //                    test2 checks setter.
|
+- xml
|  +- TEST-tests.xml // Export from Eclipse after combined test run, converted to fit Surefire format.
|
+- coverage
|  +- test1.exec // Session export from Eclipse after single test run.
|  +- test2.exec // Session export from Eclipse after single test run.
|
+- sonar-project.properties

如您所见,每个测试都有执行数据。 sonar-project.properties 的内容如下所示:

sonar.projectKey=EclipseProject
sonar.projectName=EclipseProject
sonar.projectVersion=1.0.0-20170830
sonar.projectBaseDir=/path/to/Workspace
sonar.sources=src/foo/
sonar.tests=src/tests/
sonar.sourceEncoding=UTF-8
sonar.language=java
sonar.java.source=1.8
sonar.java.binaries=bin/
sonar.java.coveragePlugin=jacoco
sonar.jacoco.reportPaths=/absolute/path/to/coverage/test1.exec,/absolute/path/to/coverage/test2.exec
sonar.junit.reportPaths=/absolute/path/to/xml/
sonar.analysis.mode=publish

我不确定缺少什么。也许文件需要以特定的方式命名,比如测试结果(只选择 Surefire 格式的 TEST-*.xml 报告)?

感谢 Sonar Java 插件的开源,我发现了问题:

  private boolean analyzeLinesCoveredByTests(String sessionId,
                      ExecutionDataStore executionDataStore) {

    int i = sessionId.indexOf(' ');
    if (i < 0) {
      return false;
    }
    String testClassName = sessionId.substring(0, i);
    String testName = sessionId.substring(i + 1);
    InputFile testResource = javaResourceLocator
                                .findResourceByClassName(testClassName);
    ...

转储会话的 ID 必须采用 testClassName testName 形式(例如,在我的例子中,test1 的 ID 为 tests.FooTestClass test1)。只有这样,您才能在 SonarQube 中看到测试覆盖率信息。