0
0
JUnittesting~15 mins

Why exception testing validates error handling in JUnit - Automation Benefits in Action

Choose your learning style9 modes available
Verify that method throws IllegalArgumentException for invalid input
Preconditions (2)
Step 1: Call calculateDiscount with a negative age value, e.g., -5
Step 2: Catch the exception thrown by the method
Step 3: Verify that the exception type is IllegalArgumentException
Step 4: Verify that the exception message contains 'Age cannot be negative'
✅ Expected Result: The method throws IllegalArgumentException with the correct message when called with negative age
Automation Requirements - JUnit 5
Assertions Needed:
Assert that IllegalArgumentException is thrown
Assert that exception message contains 'Age cannot be negative'
Best Practices:
Use assertThrows for exception testing
Check exception message to ensure correct error handling
Keep test method names descriptive
Avoid catching exceptions manually in test
Automated Solution
JUnit
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;

public class DiscountCalculatorTest {

    @Test
    void calculateDiscount_throwsException_forNegativeAge() {
        IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> {
            DiscountCalculator.calculateDiscount(-5);
        });
        assertTrue(exception.getMessage().contains("Age cannot be negative"));
    }
}

class DiscountCalculator {
    public static double calculateDiscount(int age) {
        if (age < 0) {
            throw new IllegalArgumentException("Age cannot be negative");
        }
        // Simple discount logic for example
        return age > 60 ? 0.2 : 0.0;
    }
}

This test uses assertThrows to check that the method calculateDiscount throws an IllegalArgumentException when given a negative age.

We capture the exception and then verify its message contains the expected text. This confirms the error handling works as intended.

Using assertThrows is best practice because it clearly expresses the test's purpose and avoids manual try-catch blocks.

The method calculateDiscount is a simple example that throws the exception for invalid input.

Common Mistakes - 3 Pitfalls
{'mistake': 'Catching exceptions manually inside the test method', 'why_bad': 'It makes the test code longer and less clear. It also risks missing assertion failures if exceptions are not handled properly.', 'correct_approach': "Use JUnit's assertThrows method to automatically check for exceptions."}
Not verifying the exception message
Testing exceptions with generic Exception class
Bonus Challenge

Now add data-driven testing with 3 different invalid age inputs: -1, -10, and -100

Show Hint