How to Use the @DisplayName Annotation in JUnit

Clean up your test method names with this simple annotation.

One of the most difficult problems in software development is naming. Creating meaningful names for the fundamental aspects of a program, such as classes and methods, can be tricky. Naming restrictions, such as no spacing, further amplify this problem.

The naming problem persists in every aspect of the software development life cycle, including testing. This is where the JUnit @DisplayName annotation becomes useful.

What Is the @DisplayName Annotation?

A single method can have several test methods that each test a specific behavior. However, if you assign behavioral names to test methods, they can become wordy and difficult to read.

The @DisplayName annotation is a JUnit component that allows you to create custom names for your test classes and methods. These names can have spaces, special characters, and even emojis. The @DisplayName annotation should help you create more descriptive, meaningful names for test classes and methods.

How to Use the @DisplayName Annotation

In a JUnit test class, the @DisplayName annotation appears above the class name or just before the method declaration. The @DisplayName annotation takes a single argument (the name). This argument later appears in test reports, making testing documentation more descriptive.

package displayname;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

@DisplayName("Test class demonstrating how the @DisplayName annotation works.")
class DisplayNameTest {
@DisplayName("Testing display name containing special characters: °□°)╯")
void testDisplayNameWithSpecialCharacters() {}

@DisplayName("Testing display name containing space")
void testDisplayNameWithSpaces() {}

@DisplayName("Testing display name containing emoji: 😱")
void testDisplayNameWithEmoji() {}

Executing this Java class generates the following JUnit unit test report:

Each @DisplayName annotation argument replaces its respective class or method name in the JUnit test report. The @DisplayName annotation, “Test class demonstrating how the @DisplayName annotation works” is much more expressive and comprehensive than DisplayNameTest.

What’s Next for Testing?

Knowing how to use the @DisplayName annotation will certainly improve your unit test documentation. Apart from the @DisplayName annotation, you will find that all your JUnit unit tests will need one or more assertions. Assertions are the building blocks of JUnit unit tests, therefore, it’s good to learn how to use them.