Reputation: 1893
Why these lines like method definitions (line with modifiers, method name, arguments etc) or closing brackets counts sometimes into line coverage?
In this particular example it is a constructor method, but it's not always like that:
Can you explain that?
Upvotes: 4
Views: 5223
Reputation: 48327
This depends on what coverage tool you are using, but I've seen some that match your results.
The reason, so far as I can tell, is throw/early-return vs hitting the end of the function.
Note that the only method you have with the closing brace highlighted does not return (anything), instead running off the end of the function and so touching the closing brace (and the stack-popping that probably happens there). Same for the constructor, which does not explicitly return anywhere within the function.
In the other examples, the last highlighted line is where execution leaves the function.
You can test this pretty easily by setting up a method that returns early, and testing only that case while collecting coverage. Test the other (return off the end) case with coverage, and compare the two. Hopefully, the second shows the closing brace highlighted.
For example:
public class EarlyReturn {
public static void whatHappens(final Boolean path) {
System.out.println("Entering method...");
if (path == null) {
throw new IllegalArgumentException("Must have a path.");
} else if (path) {
System.out.println("Exiting early...");
return;
}
System.out.println("Exiting normally...");
}
}
with:
@RunWith(JUnit4.class)
public class TestEarlyReturn {
@Test
public void testEarly() {
EarlyReturn.whatHappens(true);
}
@Test
public void testNormal() {
EarlyReturn.whatHappens(false);
}
@Test(expected = IllegalArgumentException.class)
public void testThrow() {
EarlyReturn.whatHappens(null);
}
}
You haven't mentioned line/branch coverage metrics, but in your example, all cases should have 100% coverage (I would hope). This, of course, still depends on the tool and how it samples. My example should not have 100% line coverage, unless you run both tests together.
Upvotes: 5