Question

Junit 5 - How to pass in multiple null values for @CsvSource?

I am modifying a test method from single parameter to multiple:

@ParameterizedTest
@NullSource
@ValueSource({"foo", "bar"..})
void shouldReturnFalse(String x) {
  assertThat(someMethod(x)).isFalse();
}

@ParameterizedTest
@CsvSource({
  "null, null",
  "foo, bar"
})
void shouldReturnFalse(String x, String y) {
  assertThat(someMethod(x, y)).isFalse();
}

null here is passed in as a String literal instead of a null literal. As a result, this test fails. This test previously works with single argument with @NullSource, but it gives following error when switched to multiple:

org.junit.jupiter.api.extension.ParameterResolutionException: No ParameterResolver registered for parameter...

I couldn't find a workaround for this and the solutions I saw were rather hacky and cumbersome. Is there a easier way for providing values with null?

 48  33723  48
1 Jan 1970

Solution

 90

@CsvSource has an attribute called nullValues. See the documentation.

A list of strings that should be interpreted as null references.

@CsvSource(value= {"null, null",
                   "foo, bar"}
           , nullValues={"null"})

The other option is to simply don't pass any value as stated in the previously linked documentation.

Please note that unquoted empty values will always be converted to null references regardless of the value of this nullValues attribute; whereas, a quoted empty string will be treated as an emptyValue().

@CsvSource({",",
            "foo, bar"})
2020-12-09

Solution

 15

You can use nullValues as explained above by @Jan Schmitz, or you can just discard null values like this:

@CsvSource({
  ",",
  "foo, bar"
})
2020-12-20