JUnit 5:访问 ParameterizedTest 内的索引

M.S*_*sti 4 java junit5

考虑这个片段:

@ParameterizedTest
@ValueSource(strings = {"a", "b", "c"})
void test(final String line) {
    // code here
}
Run Code Online (Sandbox Code Playgroud)

这将是一个实际测试,但为了简单起见,假设其目的只是打印以下内容:

Line 1: processed "a" successfully.
Line 2: processed "b" successfully.
Line 3: failed to process "c".
Run Code Online (Sandbox Code Playgroud)

换句话说,我希望测试值的索引可以在测试中访问。根据我的发现,{index}可以在测试之外使用它来正确命名。

rie*_*pil 5

我不确定 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));
  }
}
Run Code Online (Sandbox Code Playgroud)