Testing Exceptions in JUnit 5 — assertThrows and Exception Messages
Fast recall
Quick revision
Core answer
Whether the candidate can properly test exception scenarios including exception type, message, and cause chain.
Using try-catch in tests instead of assertThrows — the test passes silently if no exception is thrown.
Explain assertDoesNotThrow for negative testing, testing exception cause chains, and parameterized tests for multiple exception scenarios.
Interview-ready guide
Interview answer
Never use try-catch for exception testing — if someone removes the fail() call, the test passes when no exception is thrown. assertThrows makes the expectation explicit: if no exception is thrown, the test fails.
assertThrows returns the caught exception for further assertions — message, cause, custom fields. AssertJ's assertThatThrownBy chains these fluently: .isInstanceOf(ValidationException.class).hasMessageContaining("email").hasCauseInstanceOf(DataAccessException.class).
Two things most people miss: hasMessageContaining() is more resilient than exact message matching, and assertDoesNotThrow() explicitly tests that valid input doesn't throw. The negative test is as important as the positive one.
For services that wrap exceptions, hasCauseInstanceOf() verifies the wrapping chain — that your service caught the database error and wrapped it in a domain exception.
Testing Exceptions in JUnit 5 — assertThrows and Exception Messages
Direct Answer
JUnit 5's assertThrows captures the exception for further assertions. AssertJ's assertThatThrownBy provides fluent chaining for type, message, and cause verification.
Common Mistakes & Pitfalls
Using try-catch in tests instead of assertThrows — the test passes silently if no exception is thrown.
Related interview prep categories
1Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.