JUnit 5:在 ParameterizedTest 中访问索引
JUnit 5: Accessing index inside ParameterizedTest
考虑这个片段:
@ParameterizedTest
@ValueSource(strings = {"a", "b", "c"})
void test(final String line) {
// code here
}
这将是一个实际测试,但为简单起见,假设其目的只是打印:
Line 1: processed "a" successfully.
Line 2: processed "b" successfully.
Line 3: failed to process "c".
换句话说,我希望测试值的索引可以在测试中访问。
根据我的发现,可以在测试之外使用 {index}
来正确命名它。
我不确定 JUnit 5 目前是否支持这个。解决方法是使用 @MethodSource
并提供符合您需求的 List<Argument>
。
public class MyTest {
@ParameterizedTest
@MethodSource("methodSource")
void test(final String input, final Integer index) {
System.out.println(input + " " + index);
}
static Stream<Arguments> methodSource() {
List<String> params = List.of("a", "b", "c");
return IntStream.range(0, params.size())
.mapToObj(index -> Arguments.arguments(params.get(index), index));
}
}
考虑这个片段:
@ParameterizedTest
@ValueSource(strings = {"a", "b", "c"})
void test(final String line) {
// code here
}
这将是一个实际测试,但为简单起见,假设其目的只是打印:
Line 1: processed "a" successfully.
Line 2: processed "b" successfully.
Line 3: failed to process "c".
换句话说,我希望测试值的索引可以在测试中访问。
根据我的发现,可以在测试之外使用 {index}
来正确命名它。
我不确定 JUnit 5 目前是否支持这个。解决方法是使用 @MethodSource
并提供符合您需求的 List<Argument>
。
public class MyTest {
@ParameterizedTest
@MethodSource("methodSource")
void test(final String input, final Integer index) {
System.out.println(input + " " + index);
}
static Stream<Arguments> methodSource() {
List<String> params = List.of("a", "b", "c");
return IntStream.range(0, params.size())
.mapToObj(index -> Arguments.arguments(params.get(index), index));
}
}