Main Tutorials

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

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

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

@MethodSource is useful for me

Petula
2 years ago

Thank you!