Skip to content
Advertisement

Test Coverage: How to cover assertions?

EDIT: So It looks like JeffStorey link to the bug is correct. With assertions enabled the compiler will generate extra code. There ends up being 1 extra unreachable branch created.

One of my methods constructor has these asserts

   public Board(int w, int h) {
            assert w >= 0 : "PRE1: width should be >= 0 but is " + w;
            assert h >= 0 : "PRE2: height should be >= 0 but is " + h;
    }

I’m trying to cover it by doing this

public void testInvalidBoardWidth() {
    try {
        Board badBoard = new Board(-2, 2);
        fail();
    } catch (AssertionError err) {
        assertTrue(true);
    }
}

@Test
public void testFailBoardHeight() {
    try {
        Board InvalidBoard = new Board(2, -4);
        fail();
    } catch (AssertionError err) {
        assertTrue(true);
    }

And again with values

Board (-4 , 2) and Board (2, 2)

So I’ve tested where it fails for both asserts and passes. If i’m not mistaken that covers all cases, but using the code coverage tool eclEmma Eclipse plugin it claims it is not fully covered. I already have -ea in coverage arguments of eclipse so assertions are enabled. Are my tests incomplete, or can assertions not be fully covered? Thanks.

Advertisement

Answer

Yes, you have everything covered. There are only 3 paths here:

  • w is < 0 & h > 0
  • h is < 0 & w > 0
  • w > 0 & h > 0

You could add w < 0 & h < 0 but that wouldn’t have any higher branch coverage

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement