Bird
Raised Fist0
JUnittesting~20 mins

Checking exception message in JUnit - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Exception Message Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ assertion
intermediate
2:00remaining
Check exception message with JUnit 5
Which JUnit 5 assertion correctly verifies that a method throws an IllegalArgumentException with the message "Invalid input"?
JUnit
public void testInvalidInput() {
    // methodUnderTest throws IllegalArgumentException with message "Invalid input" when input is negative
}
AassertThrows(IllegalArgumentException.class, () -> methodUnderTest(-1), "Invalid input");
B
IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, () -> methodUnderTest(-1));
assertEquals("Invalid input", thrown.getMessage());
CassertThrows(IllegalArgumentException.class, () -> methodUnderTest(-1)).getMessage().equals("Invalid input");
DassertThatThrownBy(() -> methodUnderTest(-1)).hasMessage("Invalid input");
Attempts:
2 left
💡 Hint
Use assertThrows to capture the exception, then check its message separately.
❓ Predict Output
intermediate
2:00remaining
Output of JUnit test with exception message assertion
What is the result of running this JUnit 5 test method if methodUnderTest throws IllegalArgumentException with message "Wrong value" instead of "Invalid input"?
JUnit
import static org.junit.jupiter.api.Assertions.*;

@Test
void testExceptionMessage() {
    IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, () -> methodUnderTest(-5));
    assertEquals("Invalid input", ex.getMessage());
}

void methodUnderTest(int x) {
    if (x < 0) throw new IllegalArgumentException("Wrong value");
}
ATest fails with IllegalArgumentException but no assertion error
BTest passes successfully
CTest fails with NullPointerException
DTest fails with AssertionError: expected 'Invalid input' but was 'Wrong value'
Attempts:
2 left
💡 Hint
Check the difference between expected and actual exception messages.
🔧 Debug
advanced
2:00remaining
Identify the error in exception message assertion
What is wrong with this JUnit 5 test code that tries to check the exception message?
JUnit
assertThrows(IllegalArgumentException.class, () -> methodUnderTest(-1), msg -> assertEquals("Invalid input", msg));
AassertThrows does not accept a third argument; this causes a runtime error.
BThe lambda parameter 'msg' is a String, but assertThrows expects a Consumer<Throwable>.
CThe third argument is a failure message string, not a lambda; this causes a compilation error.
DThe lambda should return a boolean, but assertEquals returns void, causing a type mismatch.
Attempts:
2 left
💡 Hint
Check the method signature of assertThrows in JUnit 5.
❓ framework
advanced
2:00remaining
Best practice for checking exception messages in JUnit 5
Which approach is considered best practice for verifying exception messages in JUnit 5 tests?
AUse assertThrows to capture the exception, then assert the message with assertEquals separately.
BUse @Test(expected=Exception.class) annotation and check message in a separate test.
CUse assertThrows with a third argument as a lambda to check the message inline.
DUse try-catch block and fail() method to check exception message manually.
Attempts:
2 left
💡 Hint
Consider readability and clarity of test code.
🧠 Conceptual
expert
2:00remaining
Why check exception messages in tests?
Why is it important to verify the exception message in addition to the exception type in automated tests?
ABecause exception messages provide detailed context that distinguishes different error causes of the same exception type.
BBecause checking messages improves test execution speed significantly.
CBecause exception messages are required by the compiler to identify exceptions.
DBecause exception messages are always unique and guarantee no false positives.
Attempts:
2 left
💡 Hint
Think about why the same exception type might be thrown for different reasons.

Practice

(1/5)
1. In JUnit 5, which method is used to check that a specific exception is thrown with a particular message?
easy
A. assertThrows with a lambda and then assert on the exception message
B. assertEquals with the exception class
C. assertTrue with exception message string
D. assertNull with exception object

Solution

  1. Step 1: Understand how to catch exceptions in JUnit 5

    JUnit 5 uses assertThrows to check if a block of code throws an exception.
  2. Step 2: Check the exception message

    After assertThrows returns the exception, you can assert its message with assertEquals or other assertions.
  3. Final Answer:

    assertThrows with a lambda and then assert on the exception message -> Option A
  4. Quick Check:

    assertThrows + message check = A [OK]
Hint: Use assertThrows and then check message from returned exception [OK]
Common Mistakes:
  • Trying to check exception message inside assertEquals directly
  • Using assertTrue with exception message string only
  • Expecting assertNull to check exceptions
2. Which of the following is the correct syntax to assert that a method throws IllegalArgumentException with message "Invalid input" in JUnit 5?
easy
A. assertThrows(IllegalArgumentException.class, () -> method(), "Invalid input");
B. assertEquals("Invalid input", assertThrows(IllegalArgumentException.class, () -> method()).getMessage());
C. assertThrows(() -> method(), IllegalArgumentException.class).getMessage().equals("Invalid input");
D. assertThrows(IllegalArgumentException.class, () -> method()).getMessage() == "Invalid input";

Solution

  1. Step 1: Use assertThrows with exception class and lambda

    The correct order is assertThrows(ExceptionClass.class, executable lambda).
  2. Step 2: Get the exception message and compare with equals()

    Use getMessage() and equals() to compare strings, not ==.
  3. Final Answer:

    assertEquals("Invalid input", assertThrows(IllegalArgumentException.class, () -> method()).getMessage()); -> Option B
  4. Quick Check:

    assertThrows + getMessage + equals = B [OK]
Hint: Use assertEquals("msg", assertThrows(class, lambda).getMessage()) [OK]
Common Mistakes:
  • Passing message as third argument to assertThrows
  • Swapping lambda and exception class order
  • Using == to compare strings instead of equals()
3. What will be the result of this JUnit 5 test code?
Exception exception = assertThrows(NullPointerException.class, () -> { throw new NullPointerException("Null value found"); });
assertEquals("Null value found", exception.getMessage());
medium
A. Test fails because exception type does not match
B. Test fails because exception message does not match
C. Test passes because exception type and message match
D. Test throws compilation error

Solution

  1. Step 1: Check exception type thrown matches assertThrows

    The lambda throws NullPointerException, which matches the expected type.
  2. Step 2: Check the exception message matches the assertEquals

    The message "Null value found" matches exactly, so assertion passes.
  3. Final Answer:

    Test passes because exception type and message match -> Option C
  4. Quick Check:

    Exception type and message match = Pass [OK]
Hint: Exception type and message must both match for assertEquals pass [OK]
Common Mistakes:
  • Assuming assertThrows only checks type, not message
  • Confusing assertEquals order of arguments
  • Thinking test fails if exception is thrown
4. Identify the error in this JUnit 5 test code that checks exception message:
assertThrows(IllegalStateException.class, () -> { throw new IllegalStateException("Error occurred"); }, "Error occurred");
medium
A. Exception message should be checked with assertTrue, not assertThrows
B. Exception type IllegalStateException is incorrect
C. Lambda syntax is invalid
D. assertThrows does not accept a message as third argument for checking exception message

Solution

  1. Step 1: Review assertThrows method signature

    assertThrows expects (Class, Executable) or (Class, Executable, String) where String is failure message, not exception message.
  2. Step 2: Understand how to check exception message

    Exception message must be checked separately after assertThrows returns the exception.
  3. Final Answer:

    assertThrows does not accept a message as third argument for checking exception message -> Option D
  4. Quick Check:

    Third argument in assertThrows is failure message, not exception message [OK]
Hint: Third argument in assertThrows is test failure message, not exception message [OK]
Common Mistakes:
  • Passing expected exception message as third argument to assertThrows
  • Confusing failure message with exception message
  • Not capturing exception to check message separately
5. You want to test a method that throws different exceptions with different messages based on input. Which JUnit 5 approach correctly checks both exception type and message for input "bad" that throws IllegalArgumentException with message "Bad input"?
hard
A. var ex = assertThrows(IllegalArgumentException.class, () -> method("bad")); assertEquals("Bad input", ex.getMessage());
B. assertThrows(IllegalArgumentException.class, () -> method("bad"), "Bad input");
C. assertTrue(() -> method("bad").getMessage().equals("Bad input"));
D. try { method("bad"); fail(); } catch (Exception e) { assertEquals("Bad input", e.getMessage()); }

Solution

  1. Step 1: Use assertThrows to capture the exception for input "bad"

    assertThrows returns the exception object for further checks.
  2. Step 2: Assert the exception message matches expected "Bad input"

    Use assertEquals on ex.getMessage() to verify the message.
  3. Final Answer:

    var ex = assertThrows(IllegalArgumentException.class, () -> method("bad")); assertEquals("Bad input", ex.getMessage()); -> Option A
  4. Quick Check:

    Capture exception then check message separately = D [OK]
Hint: Capture exception with assertThrows, then assert message separately [OK]
Common Mistakes:
  • Passing message as third argument to assertThrows
  • Using assertTrue incorrectly with lambda
  • Not failing test if exception not thrown
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