如何自定义设置Junit 5 参数化的测试用例名称
使用字符串加Junit自带的参数
@ParameterizedTest(name = “{index}: {0}”)
@ParameterizedTest(name = “test case number is {index}”)
使用@method 封装Arguments(Name)
查看StackOverflow 以及 Junit 5 官网发现Junit 5.8 有Named 接口,提供自定义参数名称
https://stackoverflow.com/questions/57892989/generating-display-names-for-parameterizedtest-in-junit-5
https://junit.org/junit5/docs/current/user-guide/#writing-tests-parameterized-tests-display-names
@DisplayName("A parameterized test with named arguments")
@ParameterizedTest(name = "{index}: {0}")
@MethodSource("namedArguments")
void testWithNamedArguments(File file) {
}
static Stream<Arguments> namedArguments() {
return Stream.of(
arguments(named("An important file", new File("path1"))),
arguments(named("Another file", new File("path2")))
);
}
protected static Stream<Arguments> queryBusinessByKeywords() {
List<TestCase> params = XmlUtils.getXmlRecords(queryABC).stream().filter(param -> (param.getKeywords()!=null && param.getKeywords().length() > 0)).collect(Collectors.toList());
return IntStream.range(0, params.size())
.mapToObj(index -> arguments(named(params.get(index).getName(),params.get(index)), index));
}
遇到问题 当使用@ParameterizedTest()时,测试用例名会有自带的pattern, "payload = "
查看了Junit 代码,发现ARGUMENTS_PLACEHOLDER 对应的argumentsPattern 可以去除固定的pattern “payload =”
private String prepareMessageFormatPattern(int invocationIndex, Object[] arguments) {
String result = pattern//
.replace(DISPLAY_NAME_PLACEHOLDER, this.displayName)//
.replace(INDEX_PLACEHOLDER, String.valueOf(invocationIndex));
if (result.contains(ARGUMENTS_WITH_NAMES_PLACEHOLDER)) {
result = result.replace(ARGUMENTS_WITH_NAMES_PLACEHOLDER, argumentsWithNamesPattern(arguments));
}
if (result.contains(ARGUMENTS_PLACEHOLDER)) {
result = result.replace(ARGUMENTS_PLACEHOLDER, argumentsPattern(arguments));
}
return result;
}
private String argumentsWithNamesPattern(Object[] arguments) {
return IntStream.range(0, arguments.length) //
.mapToObj(index -> methodContext.getParameterName(index).map(name -> name + "=").orElse("") + "{"
+ index + "}") //
.collect(joining(", "));
}
private String argumentsPattern(Object[] arguments) {
return IntStream.range(0, arguments.length) //
.mapToObj(index -> "{" + index + "}") //
.collect(joining(", "));
}