0
0
JunitHow-ToBeginner ยท 3 min read

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 @DisplayName on test methods without importing it, leading to compilation errors.
  • Expecting @DisplayName to 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

FeatureDescriptionExample
AnnotationMarks test class or method with a display name@DisplayName("My Test")
ParameterA string describing the test"Check addition works"
ScopeCan be used on classes and methodsAbove class or method declaration
EffectChanges name shown in reports and IDEsReadable 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.