JUnit null and empty sources

A quick tip on using JUnit’s @NullAndEmptySource annotation for parameterized tests, demonstrating how to easily test null and empty string cases alongside regular test values.
Published

September 5, 2023

Today I learned about JUnit’s ability to use null sources in conjunction with @ParamterizedTest. Example:

@ParameterizedTest
@NullAndEmptySource
@ValueSource(strings = {"test", "JUnit"})
void nullAndEmptyTest(String text) {
    Assertions.assertTrue(text == null || text.trim().isEmpty() || "test".equals(text) || "JUnit".equals(text));
}

There’s also @NullSource and @EmptySource.