72

How can I write a parameterized test with two arguments in JUnit 5 jupiter? The following does not work (compile error):

@ParameterizedTest
@ValueSource(strings = { "a", "b", "foo" })
@ValueSource(ints = { 1, 2, 3 })
public void test(String arg1, int arg2) {...}
ruediste
  • 2,434
  • 1
  • 21
  • 30

1 Answers1

135

Here are two possibilities to achieve these multi argument test method calls.

The first (testParameters) uses a CsvSource to which you provide a comma separated list (the delimiter is configurable) and the type casting is done automatically to your test method parameters.

The second (testParametersFromMethod) uses a method (provideParameters) to provide the needed data.

@ParameterizedTest
@CsvSource({"a,1", "b,2", "foo,3"})
public void testParameters(String name, int value) {
    System.out.println("csv data " + name + " value " + value);
}

@ParameterizedTest
@MethodSource("provideParameters")
public void testParametersFromMethod(String name, int value) {
    System.out.println("method data " + name + " value " + value);
}

private static Stream<Arguments> provideParameters() {
    return Stream.of(
            Arguments.of("a", 1),
            Arguments.of("b", 2),
            Arguments.of("foo", 3)
    );
}

The output of these test methods are:

Running ParameterTest
csv data a value 1
csv data b value 2
csv data foo value 3
method data a value 1
method data b value 2
method data foo value 3
wumpz
  • 8,257
  • 3
  • 30
  • 25
  • 1
    Thanks a lot. Is there a way to test the cross product ("a,1","a,2","a,3","b,1","b,2",...) without writing every combination? – ruediste Apr 28 '20 at 16:16
  • 5
    For this the method approach will do the job. In provideParameters you could build up every combination you want. – wumpz Apr 29 '20 at 05:33
  • 1
    @ruediste There is already an issue about that: https://github.com/junit-team/junit5/issues/1427. – eee May 03 '20 at 09:41