@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.
5. You want to test a method that processes user input strings, including null and empty values, plus some specific strings. Which annotation combination correctly covers null, empty, and the strings "admin" and "guest" in a single parameterized test?
hard
A. @ParameterizedTest
@NullAndEmptySource
@ValueSource(strings = {"admin", "guest"})
B. @ParameterizedTest
@EmptySource
@ValueSource(strings = {"admin", "guest"})
C. @ParameterizedTest
@NullSource
@ValueSource(strings = {"admin", "guest"})
D. @ParameterizedTest
@ValueSource(strings = {null, "", "admin", "guest"})
Solution
Step 1: Identify annotations for null and empty
@NullAndEmptySource adds both null and empty string automatically.
Step 2: Add specific string inputs
@ValueSource(strings = {"admin", "guest"}) adds the required specific strings.
Step 3: Verify combined usage
Combining @NullAndEmptySource with @ValueSource covers all needed inputs in one test.
Final Answer:
@ParameterizedTest
@NullAndEmptySource
@ValueSource(strings = {"admin", "guest"}) -> Option A
Quick Check:
Use @NullAndEmptySource plus @ValueSource for all inputs [OK]
Hint: Combine @NullAndEmptySource with @ValueSource for null, empty, and values [OK]
Common Mistakes:
Using only @EmptySource or @NullSource missing one input
Trying to put null in @ValueSource strings (not allowed)
Not combining annotations properly
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.