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.

1
  • I don't think this is possible. Why would your tests need it? Commented Jun 17, 2020 at 5:09

1 Answer 1

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));
  }
}
Sign up to request clarification or add additional context in comments.

4 Comments

Great answer, thanks! I think we can let methodSource return Stream<Arguments>, and therefore there is no need to use .collect(Collectors.toList()) at the end. This was tested using JUnit 5.7.0-M1 successfully.
And by the way, just found a Guava method (currently in beta) which can do this: stackoverflow.com/a/42673873/459391.
you are right, this can be even simplified. I updated the answer. The Guava method looks promising
One technicality for future: Guava mapWithIndex uses Long indices rather than Integer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.