0
0
JUnittesting~5 mins

@NullAndEmptySource in JUnit

Choose your learning style9 modes available
Introduction

@NullAndEmptySource helps you test how your code handles empty or null inputs easily. It saves time by automatically providing these special cases to your test method.

When you want to check if your method works correctly with null input.
When you want to verify behavior with empty strings or collections.
When you want to avoid writing separate tests for null and empty values.
When you want to improve test coverage for edge cases.
When you want to catch bugs caused by missing or empty data.
Syntax
JUnit
@NullAndEmptySource
Use this annotation on a parameterized test method.
It automatically adds null and empty values as test inputs.
Examples
This test runs twice: once with null and once with an empty string.
JUnit
@ParameterizedTest
@NullAndEmptySource
void testWithNullAndEmpty(String input) {
    assertTrue(input == null || input.isEmpty());
}
This test checks behavior for null and empty lists.
JUnit
import java.util.List;

@ParameterizedTest
@NullAndEmptySource
void testListInput(List<String> list) {
    assertTrue(list == null || list.isEmpty());
}
Sample Program

This test method runs twice automatically: once with null and once with an empty string. It checks that the input is either null or empty.

JUnit
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.NullAndEmptySource;

public class ExampleTest {

    @ParameterizedTest
    @NullAndEmptySource
    void testStringIsNullOrEmpty(String input) {
        assertTrue(input == null || input.isEmpty());
    }
}
OutputSuccess
Important Notes

@NullAndEmptySource works only with parameterized tests.

It can be combined with other sources like @ValueSource for more inputs.

It helps catch bugs early by testing edge cases you might forget.

Summary

@NullAndEmptySource adds null and empty values to your tests automatically.

It is useful for testing how code handles missing or empty inputs.

Use it with @ParameterizedTest to save time and improve coverage.