我正在为我的项目编写代码覆盖率并遇到奇怪的行为。我有这样的功能
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/