4

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.

Sadeq Dousti
  • 3,346
  • 6
  • 35
  • 53

1 Answers1

5

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));
  }
}
rieckpil
  • 10,470
  • 3
  • 32
  • 56
  • Great answer, thanks! I think we can let `methodSource` return `Stream`, and therefore there is no need to use `.collect(Collectors.toList())` at the end. This was tested using JUnit 5.7.0-M1 successfully. – Sadeq Dousti Jun 17 '20 at 12:29
  • And by the way, just found a Guava method (currently in beta) which can do this: https://stackoverflow.com/a/42673873/459391. – Sadeq Dousti Jun 17 '20 at 12:42
  • 1
    you are right, this can be even simplified. I updated the answer. The Guava method looks promising – rieckpil Jun 17 '20 at 15:18
  • One technicality for future: Guava `mapWithIndex` uses `Long` indices rather than `Integer`. – Sadeq Dousti Jun 17 '20 at 16:42