Testing multiple exceptions in JUnit - Build an Automation Script
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.
Now add data-driven testing with 3 different invalid inputs to verify exceptions
Practice
Which JUnit method is best to test that a specific exception is thrown by a method?
Solution
Step 1: Understand the purpose of
This method checks if a specific exception is thrown when running a code block.assertThrows()Step 2: Compare with other assertion methods
assertEquals()checks values,assertTrue()checks boolean conditions, andassertNull()checks for null values, none test exceptions.Final Answer:
assertThrows() -> Option AQuick Check:
Test exceptions with assertThrows() [OK]
- Using assertEquals() to test exceptions
- Trying to catch exceptions manually in tests
- Confusing assertTrue() with exception testing
Which of the following is the correct syntax to test that IllegalArgumentException is thrown by myMethod() in JUnit 5?
?
Solution
Step 1: Recall assertThrows() method signature
The correct order is the exception class first, then a lambda with the code to test.Step 2: Check each option's syntax
assertThrows(IllegalArgumentException.class, () -> myMethod()); matches the correct syntax:assertThrows(Exception.class, () -> method());. Others have wrong order or missing lambda.Final Answer:
assertThrows(IllegalArgumentException.class, () -> myMethod()); -> Option CQuick Check:
Exception class first, then lambda [OK]
- Swapping parameters order in assertThrows
- Not using a lambda expression
- Passing method call instead of lambda
Given the following JUnit 5 test code, what will be the test result?
void testMultipleExceptions() {
assertThrows(NullPointerException.class, () -> { throw new NullPointerException(); });
assertThrows(IllegalStateException.class, () -> { throw new IllegalArgumentException(); });
}Solution
Step 1: Analyze first assertThrows
It expects NullPointerException and throws NullPointerException, so it passes.Step 2: Analyze second assertThrows
It expects IllegalStateException but throws IllegalArgumentException, so it fails.Final Answer:
Test fails because second assertThrows expects IllegalStateException but gets IllegalArgumentException -> Option AQuick Check:
Expected exception must match thrown exception [OK]
- Assuming any exception passes assertThrows
- Ignoring mismatch in exception types
- Thinking assertThrows catches all exceptions
Identify the error in the following JUnit 5 test code that tries to test two exceptions:
@Test
void testExceptions() {
assertThrows(NullPointerException.class, () -> method1());
assertThrows(IllegalArgumentException.class, () -> method2());
assertThrows(IllegalStateException.class, () -> method3());
}Assuming method2() throws IllegalStateException instead of IllegalArgumentException.
Solution
Step 1: Check expected vs actual exceptions for method2()
Expected is IllegalArgumentException but actual thrown is IllegalStateException, so assertThrows fails.Step 2: Confirm other assertThrows calls
Calls for method1() and method3() are correct or irrelevant to this error.Final Answer:
The second assertThrows will fail because expected and actual exceptions differ -> Option BQuick Check:
Expected exception must match thrown exception [OK]
- Assuming multiple assertThrows calls cause failure
- Ignoring mismatch in exception types
- Thinking assertThrows tests method calls, not exceptions
You want to test that a method process() throws either IOException or TimeoutException depending on conditions. Which is the best way to write JUnit 5 tests for both exceptions?
Solution
Step 1: Understand assertThrows usage
assertThrows tests one exception type per call; it cannot test multiple exceptions at once.Step 2: Best practice for multiple exceptions
Write separate tests for each expected exception to keep tests clear and focused.Final Answer:
Write two separate tests each using assertThrows for one exception -> Option DQuick Check:
One assertThrows per exception per test [OK]
- Trying to test multiple exceptions in one assertThrows
- Catching exceptions manually instead of using assertThrows
- Ignoring one exception in tests
Ready to prove it?
Pass the test and this pattern moves unknown
