Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 419
Grzegorz Piwowarek Avatar asked Oct 12 '17 14:10

Grzegorz Piwowarek


People also ask

How will you perform parameterized test cases?

There are five steps that you need to follow to create a parameterized test. Annotate test class with @RunWith(Parameterized. class). Create a public static method annotated with @Parameters that returns a Collection of Objects (as Array) as test data set.

Does JUnit support parameterized tests?

Some times we may need to run same tests with different arguments or values, Junit 5 Jupiter Parameterized tests makes it possible to run a test multiple times with different arguments. They are declared just like regular @Test methods but use the @ParameterizedTest annotation instead of @Test annotation.

Which option represents a source for parameterized tests in JUnit 5?

The @CsvSource accepts an array of comma-separated values, and each array entry corresponds to a line in a CSV file. This source takes one array entry each time, splits it by comma and passes each array to the annotated test method as separate parameters.


1 Answers

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"))
    );
}
like image 190
Sam Brannen Avatar answered Oct 18 '22 22:10

Sam Brannen