Java
@DisplayName
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.
Exercise 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().
Show example 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());
}
}
Test yourself
-
Complete the DisplayName call
@____("Kullanıcı oturum açabilmeli")
@Test
void testLogin() {
// ...
}
Show answer
@DisplayName("Kullanıcı oturum açabilmeli")
@Test
void testLogin() {
// ...
}
-
What does @DisplayName do?
- Runs the test method
- Runs the test with inputs
- Gives the test a readable name
- Runs code before the test
Show answer
Gives the test a readable name — @DisplayName gives the test a readable name.
-
Match annotations to their purpose
- @DisplayName
- Gives a readable name
- @DisplayNameGeneration
- Name format for the class
- @Test
- Marks a test method
- @Disabled
- Skips the test
Next lesson: Summary - JUnit test