Generating display names for @ParameterizedTest in JUnit 5

beatngu13 :

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 name attribute of the @ParameterizedTest annotation […]

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?

SDJ :

To indirectly achieve your goal until this is directly supported by JUnit, one can always add an argument to the test that's the desired string. The customization then needs to be done in the argument provider method.

@ParameterizedTest(name = "{index} {1}")
@MethodSource("argumentProvider")
public void testSomething(Object someObject, String niceRepresentation) {
    // Test something
}

private static Stream<Arguments> argumentProvider() {
    return Stream.of(
            Arguments.of(new Object(), "Nice 1"),
            Arguments.of(new Object(), "Nice 2")
    );
}

The drawback is that the unit tests is supplied arguments that are not used in the test's implementation, which can harm clarity, but then it becomes a trade-off with the verbose name in the test report.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=163938&siteId=1