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 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.
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.
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.
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"))
);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With