How to pass a null value in JUnit 5 parameterized tests
How to pass a null for the below parameterized tests?
@ParameterizedTest(name = "#{index} - Run test with args={0}")
@ValueSource(strings = {"", " "})
// @ValueSource(strings = {"", " ", null}) // compile error
void testBlankIncludeNull(String input) {
assertTrue(StringUtils.isBlank(input));
}
1. Solution – @NullSource
Since JUnit 5.4 and above, we can use the @NullSource to pass a null value to the parameterized tests.
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.NullSource;
@ParameterizedTest(name = "#{index} - Run test with args={0}")
@NullSource // pass a null value
@ValueSource(strings = {"", " "})
void testBlankIncludeNull(String input) {
assertTrue(StringUtils.isBlank(input));
}
Note
Also see @NullAndEmptySource and @EmptySource.
2. Solution – @MethodSource
Alternatively, we can use @MethodSource to provide arguments (including null value) for the tests.
@ParameterizedTest(name = "#{index} - Run test with args={0}")
@MethodSource("blankOrNullStrings")
void testBlankIncludeNull(String input) {
assertTrue(StringUtils.isBlank(input));
}
static Stream<String> blankOrNullStrings() {
return Stream.of("", " ", null);
}
3. Download Source Code
$ git clone https://github.com/mkyong/junit-examples
$ cd junit5-examples
@MethodSource is useful for me
Thank you!