Custom display names for parameters in JUnit - Build an Automation Script
import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.DisplayNameGeneration; import org.junit.jupiter.api.DisplayNameGenerator; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import static org.junit.jupiter.api.Assertions.assertTrue; @DisplayNameGeneration(DisplayNameGenerator.ReplaceUnderscores.class) public class CustomDisplayNameTest { @ParameterizedTest(name = "Run {index}: input={0}") @ValueSource(strings = {"apple", "banana", "cherry"}) @DisplayName("Test with custom display names for parameters") void testWithCustomDisplayNames(String fruit) { // Simple assertion to check input is not empty assertTrue(fruit.length() > 0); } }
This test class uses JUnit 5 parameterized tests to run the testWithCustomDisplayNames method with three different string inputs.
The @ParameterizedTest annotation marks the method as parameterized. The name attribute customizes the display name for each parameterized invocation, showing the index and the input value.
The @ValueSource provides the input strings.
The @DisplayName annotation sets a custom name for the test method itself.
The class-level @DisplayNameGeneration(DisplayNameGenerator.ReplaceUnderscores.class) replaces underscores with spaces in method names, improving readability.
The assertion checks that the input string is not empty, a simple valid test.
When running this test, the test report or console output will show the custom display names like "Run 1: input=apple", "Run 2: input=banana", etc.
Now add data-driven testing with 3 different inputs using @CsvSource and customize display names for each input set