0
0
JUnittesting~15 mins

Line and branch coverage in JUnit - Build an Automation Script

Choose your learning style9 modes available
Verify line and branch coverage for a simple calculator method
Preconditions (2)
Step 1: Create a Calculator class with a method 'int divide(int a, int b)' that returns a / b if b != 0, else throws IllegalArgumentException
Step 2: Write JUnit test methods to test divide with valid inputs (e.g., 10 / 2) and invalid input (e.g., 10 / 0)
Step 3: Run the tests and generate coverage report
Step 4: Check that all lines and branches in the divide method are covered
✅ Expected Result: The coverage report shows 100% line coverage and 100% branch coverage for the divide method
Automation Requirements - JUnit 5
Assertions Needed:
Assert that divide(10, 2) returns 5
Assert that divide(10, 0) throws IllegalArgumentException
Best Practices:
Use @Test annotation for test methods
Use assertThrows for exception testing
Keep tests small and focused
Use meaningful test method names
Automated Solution
JUnit
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;

class Calculator {
    public int divide(int a, int b) {
        if (b == 0) {
            throw new IllegalArgumentException("Divider cannot be zero");
        }
        return a / b;
    }
}

public class CalculatorTest {
    private final Calculator calculator = new Calculator();

    @Test
    void divide_withValidInputs_returnsQuotient() {
        int result = calculator.divide(10, 2);
        assertEquals(5, result, "10 divided by 2 should be 5");
    }

    @Test
    void divide_withZeroDivider_throwsException() {
        assertThrows(IllegalArgumentException.class, () -> calculator.divide(10, 0), "Divider zero should throw exception");
    }
}

The Calculator class has a divide method that checks if the divider is zero and throws an exception if so. Otherwise, it returns the division result.

The test class CalculatorTest has two tests: one to check normal division and one to check that dividing by zero throws the correct exception.

Using assertEquals verifies the correct output, and assertThrows verifies the exception. This covers all lines and branches in the divide method.

Running these tests with a coverage tool like Jacoco will show 100% line and branch coverage because both the true and false paths of the if statement are tested.

Common Mistakes - 3 Pitfalls
Not testing the exception case for division by zero
Using try-catch blocks instead of assertThrows for exception testing
Not asserting the result of the division
Bonus Challenge

Now add data-driven testing with 3 different valid inputs and 1 invalid input

Show Hint