Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

junit

junit5

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?

like image 623
夢のの夢 Avatar asked Dec 08 '20 21:12

夢のの夢


People also ask

How do you pass a null in a parameterized test?

Solution – @NullSource. Since JUnit 5.4 and above, we can use the @NullSource to pass a null value to the parameterized tests. Also see @NullAndEmptySource and @EmptySource.

How do you write a JUnit test case for a null check?

Assert class in case of JUnit 4 or JUnit 3 to assert using assertNull method. Assertions. assertNull() checks that object is null. In case, object is not null, it will through AssertError.

What is parameterized test in JUnit 5?

This article shows you how to run a test multiple times with different arguments, so-called 'Parameterized Tests', let see the following ways to provide arguments to the test: @ValueSource. @EnumSource.


2 Answers

@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"})
like image 134
Jan Schmitz Avatar answered Sep 18 '22 14:09

Jan Schmitz


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

@CsvSource({
  ",",
  "foo, bar"
})
like image 45
Abderrazzak Nejeoui Avatar answered Sep 19 '22 14:09

Abderrazzak Nejeoui