2

JUnit 5: Using Custom DisplayNames for Tests

 7 months ago
source link: https://www.mastertheboss.com/various-stuff/testing-java/junit-5-displayname-for-custom-test-names/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

JUnit 5 provides a powerful feature called @DisplayName, which allows you to customize the display name of your tests for better readability. In this tutorial, we will explore how to take control of your test names using the JUnit 5 DisplayNameGenerator. This feature enables you to create expressive, informative, and dynamic test names, making your test suite more readable and maintainable.

Prerequisites:

  • Basic knowledge of JUnit 5 annotations.
  • A Java project with JUnit 5 dependencies.

If you are new to JUnit 5 we recommend checking this article: JUnit 5 : Step-by-step Tutorial

Step 1: Understand @DisplayName Annotation

The @DisplayName annotation is used to provide a custom name for your test method. It enhances the readability of your tests by allowing you to use spaces, special characters, and Unicode characters in your test names. For example:

@Test
@DisplayName("Adding two numbers")
void add_two_numbers() {
Calculator calculator = new Calculator();
assertEquals(2, calculator.add(1, 1), "1 + 1 should equal 2");
@Test
@DisplayName("Adding two numbers")
void add_two_numbers() {
	Calculator calculator = new Calculator();
	assertEquals(2, calculator.add(1, 1), "1 + 1 should equal 2");
}

As you can see, by running the above Test will use as display name “Adding two numbers”:

junit 5 @DisplayName

Besides, be aware the the DisplayName will take precedence over the following annotation we will discuss in the next sections.

Step 2: Explore Default DisplayNameGenerator

JUnit 5 comes with a default DisplayNameGenerator that automatically generates display names based on the method names. While this works well for most cases, there are scenarios where you may need more control.

Here are some default DisplayNameGenerator available in Jupiter:

DisplayNameGeneratorBehavior
StandardMatches the standard display name generation behavior in place since JUnit Jupiter 5.0 was released.
SimpleRemoves trailing parentheses for methods with no parameters.
ReplaceUnderscoresReplaces underscores with spaces.
IndicativeSentencesGenerates complete sentences by concatenating the names of the test and the enclosing classes.

For example, to replace underscore with spaces for all your Tests in a Class, you can use:

@DisplayNameGeneration(DisplayNameGenerator.ReplaceUnderscores.class)
class CalculatorTests {
@Test
void add_two_numbers() {
Calculator calculator = new Calculator();
assertEquals(2, calculator.add(1, 1), "1 + 1 should equal 2");
@DisplayNameGeneration(DisplayNameGenerator.ReplaceUnderscores.class)
class CalculatorTests {

	@Test
	void add_two_numbers() {
		Calculator calculator = new Calculator();
		assertEquals(2, calculator.add(1, 1), "1 + 1 should equal 2");
	}
}

This time the Test display name will be the following one:

DisplayNameGenerator junit

Step 3: Create a Custom DisplayNameGenerator

To create a custom DisplayNameGenerator, implement the org.junit.jupiter.api.DisplayNameGenerator interface. This interface has the following methods which you need to override:

public class UppercaseDisplayNameGenerator implements DisplayNameGenerator {
@Override
public String generateDisplayNameForClass(Class<?> testClass) {
return testClass.getSimpleName().toUpperCase();
@Override
public String generateDisplayNameForNestedClass(Class<?> nestedClass) {
return nestedClass.getSimpleName().toUpperCase();
@Override
public String generateDisplayNameForMethod(Class<?> testClass, Method testMethod) {
return testMethod.getName().toUpperCase();
public class UppercaseDisplayNameGenerator implements DisplayNameGenerator {
    @Override
    public String generateDisplayNameForClass(Class<?> testClass) {
        return testClass.getSimpleName().toUpperCase();
    }

    @Override
    public String generateDisplayNameForNestedClass(Class<?> nestedClass) {
        return nestedClass.getSimpleName().toUpperCase();
    }

    @Override
    public String generateDisplayNameForMethod(Class<?> testClass, Method testMethod) {
        return testMethod.getName().toUpperCase();
    }
}

Our Custom UppercaseDisplayNameGenerator will transform to uppercase methods and classes in the Test Report.

Apply it as follows in your Class:

@DisplayNameGeneration(UppercaseDisplayNameGenerator.class)
class CalculatorTests {
@DisplayNameGeneration(UppercaseDisplayNameGenerator.class)
class CalculatorTests {
}

Here is your Test Report:

@DisplayNameGeneration junit example

Conclusion

In this tutorial, we explored the DisplayNameGenerator feature in JUnit 5, allowing us to create custom test names. By leveraging this capability, you can make your tests more descriptive, fostering better communication within your development team and making your test suite more maintainable in the long run.

Experiment with different display name strategies based on your project’s needs, and enjoy the benefits of cleaner and more informative test names. Happy testing!

Source code for this example: https://github.com/fmarchioni/mastertheboss/tree/master/test/junit5-namegeneration

Found the article helpful? if so please follow us on Socials


Recommend

  • 60

    Writing tests and test cases is important in software engineering, however, it seems that a lot of people, especially new-baked developers are afraid of...

  • 16
    • 98elements.com 4 years ago
    • Cache

    Improve your tests with JUnit 5

    Years ago JUnit 4 was number one test library among Java developers. Since its formation software development process as well as JVM has changed. Fortunately, JUnit team knew the disadvantages of their project and made gre...

  • 39

    Use GreenMail For Spring Mail (JavaMailSender) JUnit 5 Integration Tests December 22, 2020 First time here? Get an overview of all topics you'll find answers for on this blog

  • 24

    Use null values in JUnit 5 parameterized tests JUnit 5 allows you to parameterize your tests so that the same test case is executed repe...

  • 8

    Parameterized tests Junit using the file entry advertisements I have a query about using parameterized tests for my unit testing of my APIs. Now in...

  • 5

    Difference between JUnit theories and parametric tests advertisements What is the difference between a Theory and a Parameterized test?

  • 3
    • dev.to 2 years ago
    • Cache

    JUnit 5 - Writing Tests

    In JUnit 5 - Introduction we talked about JUnit and we wrote a really simple test case. In this tutorial we are going to dive in-depth to write more complex test methods.

  • 9

    Parallelize Only Java Unit Tests with JUnit 5 and MavenLast Updated:  September 26, 2022 | Published: September 26, 2022 The more our project and test suite grow, the longer the feedback loop becomes. Fort...

  • 3
    • reflectoring.io 1 year ago
    • Cache

    JUnit 5 Parameterized Tests

    JUnit 5 Parameterized Tests Table Of Contents If you’re reading this article, it means you’re already well-versed with JUnit. Let me give you a summary of JUnit - In software develop...

  • 5
    • www.mastertheboss.com 8 months ago
    • Cache

    How to run JUnit 5 Tests with JBang

    Testing RESTful Web Services -15 - ...

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK