These annotations help test methods run with special input values like null or empty data. This makes sure your code handles these cases well.
0
0
@NullSource and @EmptySource in JUnit
Introduction
When you want to check how your method behaves if it gets a null input.
When you want to test how your method handles empty strings or empty collections.
When you want to avoid writing multiple test cases for null or empty inputs manually.
When you want to improve test coverage for edge cases easily.
Syntax
JUnit
@NullSource
@EmptySource
void testMethod(Type input) { ... }@NullSource provides a single null value as input.
@EmptySource provides empty values like "" for strings, empty collections, or arrays depending on the parameter type.
Examples
This test runs once with input as null and checks if the input is null.
JUnit
@ParameterizedTest @NullSource void testWithNull(String input) { assertNull(input); }
This test runs once with an empty string and checks if the input is empty.
JUnit
@ParameterizedTest @EmptySource void testWithEmpty(String input) { assertEquals("", input); }
This test runs twice: once with null and once with empty string, checking both cases.
JUnit
@ParameterizedTest @NullSource @EmptySource void testWithNullAndEmpty(String input) { assertTrue(input == null || input.isEmpty()); }
Sample Program
This test method runs twice: once with null and once with empty string. It checks that the input is either null or empty as expected.
JUnit
import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.NullSource; import org.junit.jupiter.params.provider.EmptySource; import static org.junit.jupiter.api.Assertions.*; public class ExampleTest { @ParameterizedTest @NullSource @EmptySource void testNullAndEmptyInputs(String input) { if (input == null) { assertNull(input); } else { assertEquals("", input); } } }
OutputSuccess
Important Notes
You can combine @NullSource and @EmptySource to test both null and empty inputs easily.
@EmptySource works with strings, collections, arrays, and maps by providing their empty versions.
These annotations reduce repetitive code and improve test clarity.
Summary
@NullSource provides null input for parameterized tests.
@EmptySource provides empty input like empty string or collection.
Use them together to test edge cases simply and clearly.