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
?
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.
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.
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.
@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"})
You can use nullValues as explained above by @Jan Schmitz, or you can just discard null values like this:
@CsvSource({
",",
"foo, bar"
})
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