JUnit 5 Display Names Example

1. Overview

In this post, we will learn how to display names for Test Classes, test methods, Test Suites and display technical names of the Test Classes. we will discuss three display name annotations of JUnit 5
  • @DisplayName
  • @SuiteDisplayName
  • @UseTechnicalNames

2. DisplayNames with Examples

2.1 @DisplayName

Test classes and test methods can declare custom display names — with spaces, special characters, and even emojis — that will be displayed by test runners and test reporting.
Example: Display Names Example
package com.javadevelopersguide.junit5;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

@DisplayName("A special test case")
class DisplayNameDemo {

    @Test
    @DisplayName("Custom test name containing spaces")
    void testWithDisplayNameContainingSpaces() {
    }

    @Test
    @DisplayName("╯°□°)╯")
    void testWithDisplayNameContainingSpecialCharacters() {
    }

    @Test
    @DisplayName("😱")
    void testWithDisplayNameContainingEmoji() {
    }

}

2.2 @SuiteDisplayName

To define a custom display name for the class run via @RunWith(JUnitPlatform.class) simply annotate the class with @SuiteDisplayName and provide a custom value.
import org.junit.platform.runner.JUnitPlatform;
import org.junit.platform.suite.api.SelectPackages;
import org.junit.platform.suite.api.SuiteDisplayName;
import org.junit.runner.RunWith;

@RunWith(JUnitPlatform.class)
@SuiteDisplayName("JUnit 4 Suite Demo")
@SelectPackages("example")
public class JUnit4SuiteDemo {
}

2.3 @UseTechnicalNames

In JUnit 5, technical names are often referred to as the fully qualified name of a test class or the test method name itself.
Let’s say we have a test class with some test methods as the following:
@RunWith(JUnitPlatform.class)
@UseTechnicalNames
 class UseTechnicalNamesTest {

    @Test
    public void testPlaceOrderOK() {
        assertEquals(1, 1);
    }

    @Test
    public void testPlaceOrderWithAnonymousUser() {
        assertEquals(1, 1);
    }

    @Test
    public void testPlaceOrderWithAuthenticatedUser() {
        assertEquals(1, 1);
    }
}

3. Conclusion

In this post, we have learned the usage of three display name annotations of JUnit 5
  • @DisplayName
  • @SuiteDisplayName
  • @UseTechnicalNames

Comments