Junit 5 Coverage testing 1 of 4 branches missing

Viewed 96

My tests is showing 1 of 4 branches missing and I am not sure why.

public Classification classify() {
    if (points >= 1 && points <= 4) {
        return Classification.First;
    }

Tests I ran:

 @Test
    void Test1() {
        int p = 3;
        Grade grade = new Grade(p);
        assertEquals(grade.classify(), Classification.First);

    }


@Test
    void Test2() {
        int p = 6;
        Grade grade = new Grade(p);
        assertNotEquals(grade.classify(), Classification.First);

    }

The 1/4 branch coverage is showing on the if (points >= 1 && points <= 4) {

Not really sure which branch I am missing at this point. Any suggestions?

1 Answers

Short answer: you should test also with p < 1 so for example with p = 0.

Long answer: when testing such stuff you should always test inside bounds, outside bounds and in this case also including the bound values. Actually coverage does not even tell you about the missing cases for the included limits.

Your case points >= 1 && points <= 4 will have the following cases:

  1. points < 1
  2. points = 1
  3. points between 1 < points < 4 (so 2 or 3)
  4. points = 4
  5. points > 4

Cases 2,3,4 are considered as the same in the coverage as a branch but as a requirement they actually are not the same. We might see from the implementation (if white box testing) that there should not be problems if tested with only on evlaue in between (2,3) value 1 <= points <= 4 but if we do not know implementation (black box testing) there might be. And again it is still a good idea to test the limits even if implementation is known since implementation may change later.

Related