What is the @DisplayName annotation in JUnit 5?

The @DisplayName annotation in JUnit is used to provide a unique name for the test class and methods. In the display name, we can use spaces, special characters, and even emojis.

Example

We can use @DisplayName to give the test class and method a unique name that is easy to remember. Let's look at some JUnit Jupiter @DisplayName annotation examples.

For test class

We can use the @DisplayName annotation for the test class by applying annotation outside the class.

For methods

We can use the @DisplayName annotation for the methods by applying annotation before starting the method.

Using emojis

We can use the @DisplayName annotation with emojis. We can add emojis to the display name.

Code example

Let’s execute the codes of the above examples:

package io.educative.junit5;
import org.junit.jupiter.api.*;
import static org.junit.jupiter.api.Assertions.*;
// for the test class
@DisplayName("My demo test class")
public class DemoTest {
@Test
// for the methods
@DisplayName("@DisplayName annotation for methods")
public void DemoTestMethod() {
assertTrue(2<3);
}
@Test
// With emojis
@DisplayName("MyDemoTestMethod ☺")
void DemoTestWithEmoji(TestInfo testInfo) {
assertEquals("MyDemoTestMethod ☺", testInfo.getDisplayName());
}
}

Summary

The @DisplayName annotation in JUnit Jupiter provides no testing benefits. It can, however, be used to provide information about the test methods that appear in reporting. Any non-technical user will quickly understand that.

Copyright ©2024 Educative, Inc. All rights reserved