Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save moreau-nicolas/d2d88c1cb77b3703396c6e4dc8dfe224 to your computer and use it in GitHub Desktop.
Save moreau-nicolas/d2d88c1cb77b3703396c6e4dc8dfe224 to your computer and use it in GitHub Desktop.
An annotation to customize test name generation in JUnit5.
package test;
import org.junit.jupiter.api.DisplayNameGeneration;
import org.junit.jupiter.api.DisplayNameGenerator;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
@DisplayNameGeneration(GenerateDisplayNameFromSourceElements.ReplaceUnderscoresAndOmitParameterTypes.class)
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface GenerateDisplayNameFromSourceElements {
class ReplaceUnderscoresAndOmitParameterTypes extends DisplayNameGenerator.ReplaceUnderscores {
@Override
public String generateDisplayNameForMethod(Class<?> testClass, Method testMethod) {
var name = super.generateDisplayNameForMethod(testClass, testMethod);
return removeParameterTypes(name);
}
private static String removeParameterTypes(String name) {
return name.replaceAll("[(].*", "");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment