java - Sonar 无法覆盖调用异常抛出函数的分支

标签 java junit4 sonarqube jacoco

我正在为我的项目编写代码覆盖率并遇到奇怪的行为。我有这样的功能

public void testException(int i) throws Exception {
    if (i == 0) {
        throw new Exception("exception");
    }
}

和测试用例

@Test
public void testException() {
    try {
        mapper.testException(0);
        fail("Wrong");
    } catch (Exception ex) {
        assertEquals("exception", ex.getMessage());
    }
}

通过maven(mvn sonar:sonar)运行测试用例后,分支被Sonar覆盖。但是,如果测试的函数是这样的

public void testException(int i) throws Exception {
    if (i == 0) {
        throwException();
    }
}

public void throwException() throws Exception {
    throw new Exception("exception");
}

然后 if 分支没有被覆盖,尽管 throwException 函数的内部实际上被执行了。无论如何要克服这个问题?我需要覆盖 100% 的类(class)

最佳答案

看起来代码未被覆盖的原因在 FAQ

Code with exceptions shows no coverage. Why?

JaCoCo determines code execution with so called probes. Probes are inserted into the control flow at certain positions. Code is considered as executed when a subsequent probe has been executed. In case of exceptions such a sequence of instructions is aborted somewhere in the middle and not marked as executed.

我还是不明白为什么直接 throw 的覆盖范围仍然出现在 Sonar 上

关于java - Sonar 无法覆盖调用异常抛出函数的分支,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28132522/

相关文章:

java - 一次解压 maven 依赖项以加速 maven 构建

java - 为数据结构定义泛型/变量类型

android - 观察由另一个线程修改的对象时 Android JUnit 测试中的计时问题

java - 当方法调用与执行时完全相同时,EasyMock 对象会抛出意外的方法调用

sonarqube - Sonar 启动时的 Elasticsearch 批量索引错误

java - 将 Java 移植到 AS3

java - 为什么Eclipse和maven中的double比较不同?

sonarqube - 如何在 Eclipse 中启用/禁用来自 SonarLint 的任何规则

Sonar Qube 6.7 : how do no-admin users create a project?

java - Stardog 数据库创建给出文件未找到异常