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

4. References

mkyong

Founder of Mkyong.com, passionate Java and open-source technologies. If you enjoy my tutorials, consider making a donation to these charities.

2 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
simplechinesefood.com
4 years ago

@MethodSource is useful for me

Petula
4 years ago

Thank you!