We check exception messages to make sure the error is exactly what we expect. This helps catch bugs and confirm the program handles problems correctly.
When testing that a method throws an error for bad input.
When verifying the error message is clear and helpful to users.
When ensuring the program stops at the right place during failures.
When debugging to confirm the cause of a failure.
When writing tests for code that should prevent invalid actions.
Syntax
JUnit
assertThrows(ExpectedException.class, () -> {
// code that should throw
});
// To check message:
Exception exception = assertThrows(ExpectedException.class, () -> {
// code that should throw
});
assertEquals("Expected message", exception.getMessage());
Use assertThrows to check if an exception is thrown.
Capture the exception object to check its message with getMessage().
Examples
This checks that parsing a non-number string throws IllegalArgumentException.
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
Step 1: Review assertThrows method signature
assertThrows expects (Class, Executable) or (Class, Executable, String) where String is failure message, not exception message.
Step 2: Understand how to check exception message
Exception message must be checked separately after assertThrows returns the exception.
Final Answer:
assertThrows does not accept a message as third argument for checking exception message -> Option D
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"));