How to pass a list as a JUnit5's parameterized test parameter?

Grzegorz Piwowarek picture Grzegorz Piwowarek · Oct 12, 2017 · Viewed 8.8k times · Source

I want to parameterize my JUnit5 tests using three parameters: string, string and list<string>.

No luck so far when using @CsvSource, which is the most convenient way of passing params for my use case:

No implicit conversion to convert object of type java.lang.String to type java.util.List

The actual test is:

@ParameterizedTest()
@CsvSource(
  "2,1"
 )
fun shouldGetDataBit(first: Int, second: String, third: List<String>) {
    ...
}

Any idea if this is possible? I'm using Kotlin here but it should be irrelevant.

Answer

Sam Brannen picture Sam Brannen · Oct 13, 2017

There is no reason to use a hack as suggested by StefanE.

At this point I'm pretty sure Junit5 Test Parameters does not support anything else than primitive types and CsvSource only one allowing mixing of the types.

Actually, JUnit Jupiter supports parameters of any type. It's just that the @CsvSource is limited to a few primitive types and String.

Thus instead of using a @CsvSource, you should use a @MethodSource as follows.

@ParameterizedTest
@MethodSource("generateData")
void shouldGetDataBit(int first, String second, List<String> third) {
    System.out.println(first);
    System.out.println(second);
    System.out.println(third);
}

static Stream<Arguments> generateData() {
    return Stream.of(
        Arguments.of(1, "foo", Arrays.asList("a", "b", "c")),
        Arguments.of(2, "bar", Arrays.asList("x", "y", "z"))
    );
}