Thursday 24 June 2021

Junit5: DisplayNameGeneration: Custom display name generator

@DisplayNameGeneration annotation is used to declare a custom display name generator for the annotated test class.

 

Step 1: Define custom display name generator by implementing DisplayNameGenerator interface.

 

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;
	}

}

 

Step 2: Use @DisplayNameGeneration with custom display generator defined in step 1.

 

DisplayNameGenerationDemo.java

package com.sample.app;

import static org.junit.jupiter.api.Assertions.assertTrue;

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

import com.sample.app.generators.CustomDisplayNameGenerator;

@DisplayNameGeneration(CustomDisplayNameGenerator.class)
public class DisplayNameGenerationDemo {

	@Test
	public void helloTest() {
		assertTrue(true);
	}
}

Run the test class 'DisplayNameGenerationDemo', you will see that the custom names are reflected in junit window.


 

You can download complete working application from this link.

https://github.com/harikrishna553/junit5/tree/master/junit5-examples

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment