Bird
Raised Fist0
JUnittesting~15 mins

Testing multiple exceptions in JUnit - Build an Automation Script

Choose your learning style10 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

Practice

(1/5)
1.

Which JUnit method is best to test that a specific exception is thrown by a method?

easy
A. assertThrows()
B. assertEquals()
C. assertTrue()
D. assertNull()

Solution

  1. Step 1: Understand the purpose of assertThrows()

    This method checks if a specific exception is thrown when running a code block.
  2. Step 2: Compare with other assertion methods

    assertEquals() checks values, assertTrue() checks boolean conditions, and assertNull() checks for null values, none test exceptions.
  3. Final Answer:

    assertThrows() -> Option A
  4. Quick Check:

    Test exceptions with assertThrows() [OK]
Hint: Use assertThrows() to check exceptions directly [OK]
Common Mistakes:
  • Using assertEquals() to test exceptions
  • Trying to catch exceptions manually in tests
  • Confusing assertTrue() with exception testing
2.

Which of the following is the correct syntax to test that IllegalArgumentException is thrown by myMethod() in JUnit 5?

?
easy
A. assertThrows(myMethod(), IllegalArgumentException.class);
B. assertThrows(() -> myMethod(), IllegalArgumentException.class);
C. assertThrows(IllegalArgumentException.class, () -> myMethod());
D. assertThrows(IllegalArgumentException, myMethod());

Solution

  1. Step 1: Recall assertThrows() method signature

    The correct order is the exception class first, then a lambda with the code to test.
  2. 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.
  3. Final Answer:

    assertThrows(IllegalArgumentException.class, () -> myMethod()); -> Option C
  4. Quick Check:

    Exception class first, then lambda [OK]
Hint: Exception class first, then lambda expression [OK]
Common Mistakes:
  • Swapping parameters order in assertThrows
  • Not using a lambda expression
  • Passing method call instead of lambda
3.

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(); });
}
medium
A. Test fails because second assertThrows expects IllegalStateException but gets IllegalArgumentException
B. Test passes because both exceptions are thrown
C. Test fails because NullPointerException is not thrown
D. Test passes because assertThrows ignores exception type

Solution

  1. Step 1: Analyze first assertThrows

    It expects NullPointerException and throws NullPointerException, so it passes.
  2. Step 2: Analyze second assertThrows

    It expects IllegalStateException but throws IllegalArgumentException, so it fails.
  3. Final Answer:

    Test fails because second assertThrows expects IllegalStateException but gets IllegalArgumentException -> Option A
  4. Quick Check:

    Expected exception must match thrown exception [OK]
Hint: Exception types must match exactly in assertThrows [OK]
Common Mistakes:
  • Assuming any exception passes assertThrows
  • Ignoring mismatch in exception types
  • Thinking assertThrows catches all exceptions
4.

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.

medium
A. The test will pass because all exceptions are thrown
B. The second assertThrows will fail because expected and actual exceptions differ
C. The test will fail because assertThrows cannot be called multiple times
D. The test will fail because method3() is not called

Solution

  1. Step 1: Check expected vs actual exceptions for method2()

    Expected is IllegalArgumentException but actual thrown is IllegalStateException, so assertThrows fails.
  2. Step 2: Confirm other assertThrows calls

    Calls for method1() and method3() are correct or irrelevant to this error.
  3. Final Answer:

    The second assertThrows will fail because expected and actual exceptions differ -> Option B
  4. Quick Check:

    Expected exception must match thrown exception [OK]
Hint: Check expected vs actual exception types carefully [OK]
Common Mistakes:
  • Assuming multiple assertThrows calls cause failure
  • Ignoring mismatch in exception types
  • Thinking assertThrows tests method calls, not exceptions
5.

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?

hard
A. Use one assertThrows with both exceptions listed together
B. Use assertThrows only for the first exception and ignore the second
C. Catch exceptions manually inside one test and assert their types
D. Write two separate tests each using assertThrows for one exception

Solution

  1. Step 1: Understand assertThrows usage

    assertThrows tests one exception type per call; it cannot test multiple exceptions at once.
  2. Step 2: Best practice for multiple exceptions

    Write separate tests for each expected exception to keep tests clear and focused.
  3. Final Answer:

    Write two separate tests each using assertThrows for one exception -> Option D
  4. Quick Check:

    One assertThrows per exception per test [OK]
Hint: Test each exception in its own assertThrows call [OK]
Common Mistakes:
  • Trying to test multiple exceptions in one assertThrows
  • Catching exceptions manually instead of using assertThrows
  • Ignoring one exception in tests
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard