Created
February 17, 2020 04:03
-
-
Save syhily/61126d9f6bada360a3f9ee99c2e9a6c5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.junit.jupiter.api.DisplayNameGenerator; | |
import java.lang.reflect.Method; | |
import static java.lang.Character.isDigit; | |
import static java.lang.Character.isLetterOrDigit; | |
import static java.lang.Character.isUpperCase; | |
/** | |
* Change the camelcase or underscore method name into a readable display name | |
*/ | |
public class CamelCastDisplayNameGenerator implements DisplayNameGenerator { | |
private static final DisplayNameGenerator INTERNAL = new Standard(); | |
@Override | |
public String generateDisplayNameForClass(Class<?> testClass) { | |
return INTERNAL.generateDisplayNameForClass(testClass); | |
} | |
@Override | |
public String generateDisplayNameForNestedClass(Class<?> nestedClass) { | |
return INTERNAL.generateDisplayNameForNestedClass(nestedClass); | |
} | |
@Override | |
public String generateDisplayNameForMethod(Class<?> testClass, Method testMethod) { | |
String methodName = testMethod == null ? "" : removeExtraClassTag(testMethod.getName()); | |
return camelToText(methodName).replace("_", " "); | |
} | |
/** | |
* This method was copy from https://github.com/krasa/StringManipulation | |
*/ | |
@SuppressWarnings("squid:S3776") | |
private static String camelToText(String text) { | |
StringBuilder builder = new StringBuilder(); | |
char lastChar = ' '; | |
for (char c : text.toCharArray()) { | |
char nc = c; | |
if (isUpperCase(nc) && !isUpperCase(lastChar)) { | |
if (lastChar != ' ' && isLetterOrDigit(lastChar)) { | |
builder.append(" "); | |
} | |
nc = Character.toLowerCase(c); | |
} else if (isDigit(lastChar) && !isDigit(c)) { | |
if (lastChar != ' ') { | |
builder.append(" "); | |
} | |
nc = Character.toLowerCase(c); | |
} | |
if (lastChar != ' ' || c != ' ') { | |
builder.append(nc); | |
} | |
lastChar = c; | |
} | |
return builder.toString(); | |
} | |
/** | |
* Kotlin based test sometime would have some extra module name be appended to the test method name. | |
* We just need drop them for clean display name. | |
*/ | |
private String removeExtraClassTag(String name) { | |
String nonNullName = name == null ? "" : name; | |
if (nonNullName.contains("$")) { | |
return nonNullName.substring(0, nonNullName.indexOf('$')); | |
} else { | |
return nonNullName; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment