0
0
JUnittesting~5 mins

Checking exception message in JUnit - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the purpose of checking an exception message in a test?
To verify that the code throws the correct error with the expected message, ensuring the error is meaningful and specific.
Click to reveal answer
beginner
How do you check an exception message using JUnit 5's assertThrows?
Use assertThrows to catch the exception, then assert the message with getMessage(), for example:<br>
Exception exception = assertThrows(Exception.class, () -> method());<br>assertEquals("Expected message", exception.getMessage());
Click to reveal answer
intermediate
Why is it better to check the exception message instead of only the exception type?
Because the message gives more detail about the error cause, helping to confirm the exact failure reason, not just the error category.
Click to reveal answer
beginner
What happens if the exception message does not match the expected message in a test?
The assertion fails, and the test reports a failure showing the expected and actual messages, helping to identify the mismatch.
Click to reveal answer
beginner
Show a simple JUnit 5 test snippet that checks for IllegalArgumentException with message "Invalid input".
@Test<br>void testInvalidInput() {<br>  IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, () -> {<br>    methodThatThrows();<br>  });<br>  assertEquals("Invalid input", ex.getMessage());<br>}
Click to reveal answer
Which JUnit method is used to check that a specific exception is thrown?
AassertThrows
BassertEquals
CassertTrue
DassertNull
How do you access the message of an exception in JUnit tests?
Aexception.toString()
Bexception.message()
Cexception.getMessage()
Dexception.getError()
Why should you check the exception message in addition to the exception type?
ATo make tests run faster
BTo confirm the exact error reason
CTo avoid catching exceptions
DTo ignore error details
What happens if the exception message does not match the expected message in a test?
AThe test fails
BThe test passes
CThe exception is ignored
DThe test is skipped
Which of these is a correct way to check exception message in JUnit 5?
AassertTrue(method().throwsException());
BassertThrows(Exception.class, () -> method(), "msg");
CassertEquals("msg", method().getMessage());
DException e = assertThrows(Exception.class, () -> method()); assertEquals("msg", e.getMessage());
Explain how to write a JUnit test that verifies both the type and message of an exception.
Think about how to capture and check exception details step by step.
You got /4 concepts.
    Why is checking the exception message important in software testing?
    Consider what information the message provides beyond the exception type.
    You got /4 concepts.