Search code examples
javamaventestingtest-coveragemaven-cobertura-plugin

Why is my branch coverage rate and line coverage rate failing?


Consider the following code:

  @Test
    public final void testIsUnitInvalidSadCase() {
    boolean expectedResult = false;
    boolean actualResult = false;
    double invalidUnit = 0.0;

    testFuelUnitValidator =
        new FuelUnitValidator(
            defaultTimestamp,
            defaultFluids,
            invalidUnit);

    actualResult = testFuelUnitValidator.isUnitInvalid();

    assertThat(actualResult, is(equalTo(expectedResult)));
}

@Test
public final void testIsUnitInvalidHappyCase() {
    boolean expectedResult = false;
    boolean actualResult = true;
    double invalidUnit = 0.02;

    testFuelUnitValidator =
        new FuelUnitValidator(
            defaultTimestamp,
            defaultFluids,
            invalidUnit);

    actualResult = testFuelUnitValidator.isUnitInvalid();

    assertThat(actualResult, is(equalTo(expectedResult)));
}

This is the method:

public boolean isUnitInvalid() {
    if (Math.abs(unit) < 0.0) {
        return true;
    }
    return false;
}

When I change the line as if (Math.abs(smu) <= 0.01) and the test classes as boolean expectedResult = true; for the first test then the maven builds up fine. But when I try to build with above code, maven throws an error as: [ERROR] *className failed check. Branch coverage rate of 95.8% is below 100.0% *className failed check. Line coverage rate of 97.8% is below 100.0%


Solution

  • When you use 0.01 in the method under test, your two tests exercise both parts (return statements) of the method. So, you get 100% coverage.

    When you use 0.00 in the method under test, both of your tests only exercise the "false" exit. There is no coverage of the "return false;" statement. So you get less than 100% coverage.