Parameterized Test with two Arguments in JUnit 5 jupiter

18,094

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
Share:
18,094
ruediste
Author by

ruediste

I'm a passionate programmer currently doing mostly Java. In the past I've been into low level programming such as assembler and C++.

Updated on June 02, 2022

Comments

  • ruediste
    ruediste almost 2 years

    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) {...}