How to Use @DisplayName in JUnit for Clear Test Names
Use the
@DisplayName annotation in JUnit to give your test methods or classes a custom, readable name that appears in test reports and IDEs. Simply place @DisplayName("Your descriptive name") above the test method or class declaration.Syntax
The @DisplayName annotation takes a single string parameter that describes the test method or class. This string is shown in test reports and IDE test runners instead of the method or class name.
- @DisplayName: The annotation itself.
- "Your descriptive name": A string that describes the test clearly.
java
@DisplayName("Descriptive test name") void testMethod() { // test code }
Example
This example shows how to use @DisplayName on a test class and test methods to give them clear, human-readable names.
java
import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; @DisplayName("Calculator Tests") class CalculatorTest { @Test @DisplayName("Addition of two positive numbers") void testAddition() { int result = 2 + 3; assertEquals(5, result); } @Test @DisplayName("Subtraction resulting in negative number") void testSubtraction() { int result = 2 - 5; assertEquals(-3, result); } }
Output
Calculator Tests
Addition of two positive numbers - PASSED
Subtraction resulting in negative number - PASSED
Common Pitfalls
Common mistakes when using @DisplayName include:
- Not using quotes around the display name string, which causes a syntax error.
- Using
@DisplayNameon test methods without importing it, leading to compilation errors. - Expecting
@DisplayNameto change the method name in code; it only changes the name shown in reports and IDEs.
java
/* Wrong usage: missing quotes causes error */ @DisplayName(Descriptive test name) void testMethod() {} /* Correct usage: quotes around string */ @DisplayName("Descriptive test name") void testMethod() {}
Quick Reference
| Feature | Description | Example |
|---|---|---|
| Annotation | Marks test class or method with a display name | @DisplayName("My Test") |
| Parameter | A string describing the test | "Check addition works" |
| Scope | Can be used on classes and methods | Above class or method declaration |
| Effect | Changes name shown in reports and IDEs | Readable test names instead of method names |
Key Takeaways
Use @DisplayName to give tests clear, readable names in reports and IDEs.
Always put the display name string in quotes to avoid syntax errors.
@DisplayName works on both test classes and test methods.
It does not change the actual method name, only the displayed name.
Remember to import org.junit.jupiter.api.DisplayName to use the annotation.