Testing / JUnit6 Interview Questions
What is the @DisplayNameGeneration annotation in JUnit 6?
@DisplayNameGeneration automatically generates human-readable display names for all test methods in a class without requiring a @DisplayName on each method. It transforms method names (which must follow identifier rules) into more readable strings.
import org.junit.jupiter.api.DisplayNameGeneration; import org.junit.jupiter.api.DisplayNameGenerator; // Converts method names to sentences: // - Removes underscores // - Removes trailing parentheses // "it_should_return_empty_when_null()" -> "it should return empty when null" @DisplayNameGeneration(DisplayNameGenerator.ReplaceUnderscores.class) class OrderServiceDisplayTest { @Test void new_order_has_pending_status() { ... } // Displayed as: "new order has pending status" @Test void order_with_invalid_quantity_throws_exception() { ... } // Displayed as: "order with invalid quantity throws exception" } // IndicativeSentences: generates "ClassName, method name" @DisplayNameGeneration(DisplayNameGenerator.IndicativeSentences.class) class PaymentTest { @Test void processValidPayment() { ... } // Displayed as: "PaymentTest, processValidPayment()" } // Custom generator: public class CamelCaseToSentenceGenerator implements DisplayNameGenerator { @Override public String generateDisplayNameForClass(Class<?> cls) { return splitCamelCase(cls.getSimpleName()); } @Override public String generateDisplayNameForNestedClass(Class<?> cls) { return splitCamelCase(cls.getSimpleName()); } @Override public String generateDisplayNameForMethod(Class<?> cls, Method method) { return splitCamelCase(method.getName()); } private String splitCamelCase(String name) { return name.replaceAll("([A-Z])", " $1").trim().toLowerCase(); } } // Set globally in junit-platform.properties: // junit.jupiter.displayname.generator.default= // org.junit.jupiter.api.DisplayNameGenerator$ReplaceUnderscores
More Related questions...