首页 > 解决方案 > JUnit 5:在 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}可以在测试之外使用它来正确命名。

标签: javajunit5

解决方案


我不确定 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));
  }
}

推荐阅读