JUnit 5: Accessing index inside ParameterizedTest

Viewed 936

Consider this snippet:

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

This will be an actual test, but for simplicity assume its purpose is to only print this:

Line 1: processed "a" successfully.
Line 2: processed "b" successfully.
Line 3: failed to process "c".

In other words, I want the index of the test values to be accessible within the test. From what I found, {index} can be used outside the test to name it properly.

1 Answers

I am not sure if JUnit 5 currently supports this. A workaround could be to use @MethodSource and provide a List<Argument> matching your needs.

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));
  }
}
Related