0
0
JUnittesting~15 mins

Testing multiple exceptions in JUnit - Build an Automation Script

Choose your learning style9 modes available
Verify method throws correct exceptions for invalid inputs
Preconditions (2)
Step 1: Call processInput with null
Step 2: Verify that IllegalArgumentException is thrown
Step 3: Call processInput with a negative number
Step 4: Verify that IndexOutOfBoundsException is thrown
✅ Expected Result: The method throws IllegalArgumentException when input is null and IndexOutOfBoundsException when input is negative
Automation Requirements - JUnit 5
Assertions Needed:
assertThrows for IllegalArgumentException when input is null
assertThrows for IndexOutOfBoundsException when input is negative
Best Practices:
Use assertThrows to verify exceptions
Write separate test methods for each exception case
Use descriptive test method names
Avoid catching exceptions manually in tests
Automated Solution
JUnit
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;

public class InputProcessorTest {

    // Class under test
    static class InputProcessor {
        public void processInput(Integer input) {
            if (input == null) {
                throw new IllegalArgumentException("Input cannot be null");
            }
            if (input < 0) {
                throw new IndexOutOfBoundsException("Input cannot be negative");
            }
            // Normal processing logic here
        }
    }

    private final InputProcessor processor = new InputProcessor();

    @Test
    void shouldThrowIllegalArgumentExceptionWhenInputIsNull() {
        assertThrows(IllegalArgumentException.class, () -> processor.processInput(null));
    }

    @Test
    void shouldThrowIndexOutOfBoundsExceptionWhenInputIsNegative() {
        assertThrows(IndexOutOfBoundsException.class, () -> processor.processInput(-1));
    }
}

This test class InputProcessorTest tests the processInput method for two exception cases.

The processInput method throws IllegalArgumentException if the input is null, and IndexOutOfBoundsException if the input is negative.

Each test method uses assertThrows from JUnit 5 to check that the correct exception is thrown for the given invalid input.

Separate test methods with descriptive names make it clear what each test verifies.

This approach avoids manual try-catch blocks and uses JUnit's built-in assertion for exceptions, which is a best practice.

Common Mistakes - 3 Pitfalls
{'mistake': 'Catching exceptions manually inside test methods', 'why_bad': 'It makes tests verbose and can hide failures if exceptions are not rethrown or asserted properly.', 'correct_approach': "Use JUnit's assertThrows method to check for exceptions cleanly and clearly."}
Testing multiple exceptions in a single test method
Not verifying the exception type and only checking if any exception is thrown
Bonus Challenge

Now add data-driven testing with 3 different invalid inputs to verify exceptions

Show Hint