I have a bunch of @ParameterizedTests that receive parameters from a @MethodSource with quite verbose toString() results (e.g. Selenium's WebDriver). These are used per default to compose the corresponding display names. From the JUnit 5 user guide:
By default, the display name of a parameterized test invocation contains the invocation index and the String representation of all arguments for that specific invocation. However, you can customize invocation display names via the
nameattribute of the@ParameterizedTestannotation […]
While this allows customizing the display names to a certain degree, it seems like I cannot adapt the string representation of the individual parameters. Unfortunately, specifying a generator via @DisplayNameGeneration can only be applied at the class level and doesn't affect the display name of the parameterized test invocations.
Is there a way to use a DisplayNameGenerator for @ParameterizedTest or to customize the string representation of the given parameters?
As of JUnit 5.8.0, there is a Named<T> interface as part of the JUnit Jupiter API with "automatic support for injecting the contained payload [the arguments] into parameterized methods directly" (see issue #2301). Example:
@DisplayName("A parameterized test with named arguments")
@ParameterizedTest
@MethodSource("namedArguments")
void testWithNamedArguments(File file) {}
static Stream<Arguments> namedArguments() {
return Stream.of(
Arguments.of(Named.of("An important file", new File("path1"))),
Arguments.of(Named.of("Another file", new File("path2")))
);
}
If you prefer static imports, you can also go for the corresponding aliases from Arguments and Named:
arguments(named("An important file", new File("path1")))
JUnit 5.11.0 also allows to provide a name for an entire set of arguments:
argumentSet("Important files", new File("path1"), new File("path2"))
For more information, please refer to the corresponding docs.