Test method with @NullAndEmptySource to handle null and empty strings
Preconditions (2)
✅ Expected Result: The test runs twice: once with null input and once with empty string input, both passing the assertion
import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.NullAndEmptySource; import static org.junit.jupiter.api.Assertions.*; public class NullAndEmptySourceTest { @ParameterizedTest @NullAndEmptySource void testNullAndEmptyStrings(String input) { assertTrue(input == null || input.isEmpty(), "Input should be null or empty"); } }
This test class uses JUnit 5's @ParameterizedTest combined with @NullAndEmptySource to run the test method twice: once with null and once with an empty string.
The test method testNullAndEmptyStrings takes a String input parameter. The assertion checks if the input is either null or empty using input == null || input.isEmpty(). If this condition is true, the test passes.
This approach is simple and effective to verify that the code handles null and empty string inputs correctly.
Now add data-driven testing with @ValueSource to test additional strings along with null and empty
@NullAndEmptySource in JUnit tests?@NullAndEmptySource in a JUnit 5 parameterized test method?@ParameterizedTest
@NullAndEmptySource
@ValueSource(strings = {"hello", "world"})
void testStrings(String input) {
// test logic here
}@NullAndEmptySource:
@ParameterizedTest
@NullAndEmptySource
void testInput() {
// test logic
}Pass the test and this pattern moves unknown