Thursday, 24 June 2021

Junit5: Setup default display name generator for all the tests

Create a file 'junit-platform.properties' under src/test/resources and add the property ‘junit.jupiter.displayname.generator.default’.

 

For example, I define my custom display name generator like below.

 

CustomDisplayNameGenerator.java

package com.sample.app.generators;

import java.lang.reflect.Method;

import org.junit.jupiter.api.DisplayNameGenerator;

public class CustomDisplayNameGenerator implements DisplayNameGenerator {

  @Override
  public String generateDisplayNameForClass(Class<?> testClass) {
    String name = testClass.getName();
    int lastDot = name.lastIndexOf('.');
    return name.substring(lastDot + 1);
  }

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

  @Override
  public String generateDisplayNameForMethod(Class<?> testClass, Method testMethod) {
    String className = generateDisplayNameForClass(testClass);
    String methodName = testMethod.getName();

    return className + "_" + methodName;
  }

}

 

Updated the file ‘src/test/resources/junit-platform.properties’ with default display name generator setting.

 

junit-platform.properties

junit.jupiter.displayname.generator.default=com.sample.app.generators.CustomDisplayNameGenerator

  When I ran the test cases, I can see that test method names in junit report follow the conventions specified in CustomDisplayNameGenerator class.

 



Display name for a test class or method is determined according to the following precedence rules:

 

a.   value of the @DisplayName annotation, if present

b.   by calling the DisplayNameGenerator specified in the @DisplayNameGeneration annotation, if present

c.    by calling the default DisplayNameGenerator configured via the configuration parameter, if present

d.   by calling org.junit.jupiter.api.DisplayNameGenerator.Standard

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment