@DisplayName
- Java course
- Advanced
- Lesson 47/82
- 5 min
Learn test naming with @DisplayName.
@DisplayName
@DisplayName gives a test class or method a human-readable name. The default name is the method name; this annotation shows a more meaningful label.
@DisplayName("Add item to cart")
@Test
void testAdd() {
// ...
}The IDE and reports show this name. This makes test results easier to read; instead of a technical name, a business-meaningful text is used. Emojis and special characters are also supported, but plain text is preferred in professional projects.
@DisplayNameGeneration
At class level, @DisplayNameGeneration sets an automatic format for all test names. This saves writing @DisplayName on every method.
@DisplayNameGeneration(ReplaceUnderscores.class)
class CartTest {
@Test
void adds_item_to_cart() { }
}Underscores turn into spaces; the test report shows "adds item to cart". This is the automatic way to get meaningful names. Teams can agree on a common format and stay consistent.
Practice Add @DisplayName to a cart test
Define a CartTest class. Declare a List<String> cart field. Write a @DisplayName("Adds item to cart") and @Test method testAdd that calls cart.add("bread") and verifies with assertEquals(1, cart.size()). Add a main method that adds one item and prints size().
Starter code
import org.junit.jupiter.api.*;
import java.util.*;
// Define the CartTest class
// Write testAdd with the name annotation and the test annotation
// Add a main method that prints cart.size()Sample solution
import org.junit.jupiter.api.*;
import java.util.*;
class CartTest {
List<String> cart = new ArrayList<>();
@DisplayName("Adds item to cart")
@Test
void testAdd() {
cart.add("bread");
assertEquals(1, cart.size());
}
public static void main(String[] args) {
CartTest t = new CartTest();
t.cart.add("bread");
System.out.println(t.cart.size());
}
}Expected output
1
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the DisplayName call
@____("Kullanıcı oturum açabilmeli")
@Test
void testLogin() {
// ...
}
@DisplayName("Kullanıcı oturum açabilmeli")
@Test
void testLogin() {
// ...
}
Explanation: @DisplayName provides a readable name.
2 What does @DisplayName do?
- Runs the test method
- Runs the test with inputs
- Gives the test a readable name Correct answer
- Runs code before the test
Explanation: @DisplayName gives the test a readable name.
3 Match annotations to their purpose
| Term | Meaning |
|---|---|
@DisplayName |
Gives a readable name |
@DisplayNameGeneration |
Name format for the class |
@Test |
Marks a test method |
@Disabled |
Skips the test |