1. Junit 5 Display Names

Junit 5 @DisplayName : In Junit 5 test classes and test methods can declare custom display names via Junit 5 @DisplayName annotation.

We can display names with spaces, special characters, and even emojis. That names will be displayed in test reports and by test runners and IDEs. Let’s go through an example to see how the Junit 5 @DispalyName works.

Technologies used :

  1. Junit 5.5.2
  2. Maven 3
  3. Java 8
  4. Spring Tool Suite 3.9.8

Junit 5 Dispaly Names example maven project :

Junit 5 @DisplayName example

Junit5DiplayNameTest.java

Copy to Clipboard

Test Results

Junit 5 @DisplayName test results 1

2. Display Name Generators

2.1. JUnit Jupiter supports custom display name generators that can be configured via the @DisplayNameGeneration annotation.

2.2. Values provided via @DisplayName annotations always take precedence over display names generated by a DisplayNameGenerator.

2.3. This example uses the JUnit ReplaceUnderscores generator to replace the underscores with spaces.

Junit5_Diplay_Name_Generator_Test.java

Copy to Clipboard

Test Results

Junit-5-@DisplayNameGeneration-test-results

3. Custom Display Name Generators

3.1. We can extend the JUnit DisplayNameGenerator to create our custom display name generator.

Copy to Clipboard

Test Results

Junit-5-custom-display-name-test-results

4. Setting the Default Display Name Generator

4.1. We can also set default DisplayNameGenerator that can be used by default if we do not use @DisplayName annotation explicitly to the each Junit 5 test case.

4.2. We need to set junit.jupiter.displayname.generator.default configuration parameter to specify the fully qualified class name of the DisplayNameGenerator you would like to use by default.you can specify the fully qualified name of any custom class that implements DisplayNameGenerator.

junit-platform.properties in src/test/resources :

Copy to Clipboard

In summary, the display name for a test class or method is determined according to the following precedence rules:

  1. value of the @DisplayName annotation, if present
  2. by calling the DisplayNameGenerator specified in the @DisplayNameGeneration annotation, if present
  3. by calling the default DisplayNameGenerator configured via the configuration parameter, if present
  4. by calling org.junit.jupiter.api.DisplayNameGenerator.Standard