Custom names

The last feature related with parameterized tests in JUnit 5 has to do with the display name of each execution of tests. As we learned, a parameterized test is usually executed as several single tests. Therefore, for the shake of traceability, it is good practice to link each test execution with the argument source.

To that aim, the annotation @ParameterizedTest accepts an element called name in which we can specify a custom name (String) for the test execution. Moreover, in this String, we can use several built-in placeholders, as described in the following table:

Placeholder

Description

{index}

Current invocation index (first one is 1, second is 2, …)

{arguments}

Comma-separated arguments complete list

{0}, {1}, …

Value for an individual argument (first one is 0, second is 2, …)

 

Let’s see a simple example. The following class contains a parameterized test whose arguments are defined using a @CsvSource annotation. The test method accepts two arguments (String and int). In addition, we are specifying the element name of the annotation @ParameterizedTest with a custom message, using the placeholders for the current test invocation ({index}) and also for the values of each argument: the first one ({0}) and the second one ({1}):

package io.github.bonigarcia;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;

class
CustomNamesParameterizedTest {

@DisplayName("Display name of test container")
@ParameterizedTest(name = "[{index}] first argument="{0}", second
argument={1}")
@CsvSource({ "mastering, 1", "parameterized, 2", "tests, 3" })
void testWithCustomDisplayNames(String first, int second) {
System.out.println("Testing with parameters: " + first + " and " +
second);
}

}

When executing this test in an IDE (IntelliJ in the following screenshot), we can see how the display name is different for each test execution:

Execution of parameterized tests using custom names in IntelliJ IDE
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.235.219