Assertion Failure Messages JUnit 5 | Java Fresher
Fast recall
Quick revision
Core answer
assertEquals(expected, actual, "premium discount"). In Jupiter assertion overloads the message or Supplier comes last; a supplier is evaluated only on failure. AssertJ uses as(...) or describedAs(...) before the assertion.Interview-ready guide
Interview answer
JUnit already shows expected and actual values, so I add a custom message only when it contributes missing context—for example, assertEquals(90, total, "premium order should receive 10% discount"). In Jupiter assertion overloads, the optional message comes last. When building it is expensive, I pass a Supplier so JUnit evaluates it only if the assertion fails. A clear test name and a precise assertion may already make a custom message unnecessary. With AssertJ, as(...) or describedAs(...) adds the same kind of context before the final assertion.
Assertion Failure Messages JUnit 5 | Java Fresher
Direct Answer
JUnit already reports expected and actual values, so add a custom message when it supplies missing context such as the scenario or business rule: assertEquals(expected, actual, "premium discount"). In Jupiter assertion overloads the message or Supplier<String> comes last; a supplier is evaluated only on failure. AssertJ uses as(...) or describedAs(...) before the assertion.
Deep Dive & Architecture
JUnit already prints expected and actual values, so a custom message should add the missing context: the scenario or business rule that failed. In JUnit 5 the message is the final argument of an assertion.
For example, assertEquals(90, total, "premium order should receive 10% discount") is more useful in CI than assertEquals(90, total), because it identifies the rule without opening the test. Avoid messages that merely repeat “values differ.” When building the message is expensive, pass a Supplier<String> such as () -> render(order); JUnit evaluates it only after a failure. AssertJ provides the same descriptive idea through as(...) or describedAs(...) before the final assertion.
Common Mistakes & Pitfalls
- JUnit 4 parameter order. In Jupiter assertion overloads, the message follows the values or executable.
- Forcing a message onto every assertion. A descriptive test name and JUnit's expected/actual output may already be enough.
- Eager expensive messages. Use a Supplier when constructing the message has meaningful cost.
- Restating the assertion. Add the scenario or rule rather than saying only "values should be equal".
Check your understanding
Answer these without looking back at the article.
- What is the Arrange-Act-Assert (AAA) pattern in unit testing?
- How do you use assertThrows to test exception scenarios in JUnit 5?
- How do you test floating point numbers in JUnit 5?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.