|
| 1 | +package com.contentstack.cms; |
| 2 | + |
| 3 | +import org.junit.jupiter.api.DisplayNameGenerator; |
| 4 | + |
| 5 | +import java.lang.reflect.Method; |
| 6 | +import java.util.Arrays; |
| 7 | +import java.util.HashSet; |
| 8 | +import java.util.Set; |
| 9 | + |
| 10 | +/** |
| 11 | + * Generates human-readable display names for every test that has no explicit |
| 12 | + * {@code @DisplayName} - e.g. {@code testAllInvitationWithQuery()} becomes |
| 13 | + * "should fetch all invitation with query". Registered globally via |
| 14 | + * {@code junit.jupiter.displayname.generator.default} in |
| 15 | + * {@code junit-platform.properties}; explicit annotations always win. |
| 16 | + */ |
| 17 | +public class TestDisplayNameGenerator extends DisplayNameGenerator.Standard { |
| 18 | + |
| 19 | + /** verbs that read naturally with a "should <verb> ..." prefix */ |
| 20 | + private static final Set<String> VERBS = new HashSet<>(Arrays.asList( |
| 21 | + "create", "fetch", "find", "get", "update", "delete", "upload", "replace", |
| 22 | + "publish", "unpublish", "localize", "unlocalize", "move", "import", "export", |
| 23 | + "clone", "deploy", "share", "unshare", "transfer", "accept", "reject", |
| 24 | + "login", "logout", "validate", "verify", "handle", "return", "reorder", |
| 25 | + "generate", "download", "setup", "throw", "reset", "activate", "deactivate")); |
| 26 | + |
| 27 | + @Override |
| 28 | + public String generateDisplayNameForClass(Class<?> testClass) { |
| 29 | + return splitCamelCase(testClass.getSimpleName()); |
| 30 | + } |
| 31 | + |
| 32 | + @Override |
| 33 | + public String generateDisplayNameForMethod(Class<?> testClass, Method testMethod) { |
| 34 | + String name = testMethod.getName(); |
| 35 | + // strip common prefixes |
| 36 | + if (name.startsWith("test")) { |
| 37 | + name = name.substring(4); |
| 38 | + } |
| 39 | + String sentence = splitCamelCase(name).toLowerCase(); |
| 40 | + if (sentence.isEmpty()) { |
| 41 | + return testMethod.getName(); |
| 42 | + } |
| 43 | + String firstWord = sentence.split(" ")[0]; |
| 44 | + if (VERBS.contains(firstWord)) { |
| 45 | + return "should " + sentence; |
| 46 | + } |
| 47 | + // capitalize the first letter for non-verb starts, e.g. "All invitation with query" |
| 48 | + return Character.toUpperCase(sentence.charAt(0)) + sentence.substring(1); |
| 49 | + } |
| 50 | + |
| 51 | + private static String splitCamelCase(String s) { |
| 52 | + return s |
| 53 | + // lower-to-upper boundary: fetchAll -> fetch All |
| 54 | + .replaceAll("([a-z0-9])([A-Z])", "$1 $2") |
| 55 | + // acronym-to-word boundary: APITest -> API Test |
| 56 | + .replaceAll("([A-Z]+)([A-Z][a-z])", "$1 $2") |
| 57 | + // letter-digit boundary: fetch2 -> fetch 2 |
| 58 | + .replaceAll("([a-zA-Z])(\\d)", "$1 $2") |
| 59 | + .replace('_', ' ') |
| 60 | + .trim(); |
| 61 | + } |
| 62 | +} |
0 commit comments