0
0
JunitHow-ToBeginner ยท 3 min read

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 MethodCustom Message PositionDescription
assertEqualsFirst argumentChecks equality with message on failure
assertTrueFirst argumentChecks condition true with message
assertFalseFirst argumentChecks condition false with message
assertNullFirst argumentChecks null with message
assertNotNullFirst argumentChecks 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.