How to Use Custom Assertion Message in JUnit Tests
In JUnit, you can add a custom assertion message by passing a
String as the first argument to assertion methods like assertEquals or assertTrue. This message will display when the assertion fails, helping you understand the test failure better.Syntax
The general syntax for adding a custom message in JUnit assertions is:
assertEquals(String message, expected, actual)assertTrue(String message, condition)assertFalse(String message, condition)
The message is a String shown only if the assertion fails. It helps explain what went wrong.
java
assertEquals("Custom failure message", expectedValue, actualValue); assertTrue("Condition should be true", condition);
Example
This example shows a JUnit test with a custom assertion message. If the test fails, the message helps identify the problem quickly.
java
import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; public class CustomMessageTest { @Test void testSum() { int expected = 5; int actual = 2 + 2; assertEquals("Sum should be 5 but was different", expected, actual); } }
Output
org.opentest4j.AssertionFailedError: Sum should be 5 but was different ==> expected: <5> but was: <4>
Common Pitfalls
Common mistakes when using custom messages include:
- Not providing a message, which makes failures harder to understand.
- Passing the message as the last argument (wrong order).
- Using complex expressions inside the message that slow down tests.
Always put the message as the first argument and keep it clear and concise.
java
/* Wrong: message as last argument */ assertEquals(expected, actual, "This is wrong order"); /* Right: message as first argument */ assertEquals("Correct order message", expected, actual);
Quick Reference
| Assertion Method | Custom Message Position | Description |
|---|---|---|
| assertEquals | First argument | Checks equality with message on failure |
| assertTrue | First argument | Checks condition true with message |
| assertFalse | First argument | Checks condition false with message |
| assertNull | First argument | Checks null with message |
| assertNotNull | First argument | Checks not null with message |
Key Takeaways
Always put the custom message as the first argument in JUnit assertions.
Use clear and concise messages to explain why the test should pass.
Custom messages appear only when assertions fail, aiding debugging.
Avoid complex expressions inside messages to keep tests fast.
Common assertion methods like assertEquals and assertTrue support custom messages.