问题
I am trying improve line coverage for my code. A line gets executed where i am calling a method which in turn will throw an exception. But line coverage shows red color meaning the line was not executed.
Code:
1 public void myMethod(SomeService someService){
2 throwException(someService);
3 }
4 public void throwException(SomeService someService){
5 THROW an exception here
6 }
In my test class I am preparing SomeService required data and calling myMethod from above code. line # 2 shows red color even though the line gets executed and throws exception as expected. Please suggest how can i show the line covered to increase the line coverage.
回答1:
Please use search before posting questions, because this is widely known JaCoCo limitation described both in EclEmma FAQ and in JaCoCo FAQ:
Source code lines with exceptions show 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 the corresponding line of source code is not marked as covered.
In other words: if method call always throws exception like in your example, then line of this method call will never be marked as fully covered aka green. The only way to see line with method call as covered - is to have an execution/test, when this method call does not throw exception.
回答2:
I can't tell from you example, but I have messed up tests before because I wasn't specific enough with the exceptions. Perhaps an exception is being thrown, but not the one you are expecting? For me, in unit tests, it is very easy to have a NullPointerException be thrown. Perhaps it is being thrown, which is causing your test to pass, but code coverage to not show as covered?
来源:https://stackoverflow.com/questions/54032393/eclemmajacocco-shows-line-not-covered-even-if-the-line-is-executed