简体   繁体   中英

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

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.

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

Provide the third element as a comma separated string and the split the string into a List inside you test.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM