0
0
JUnittesting~15 mins

@NullAndEmptySource in JUnit - Build an Automation Script

Choose your learning style9 modes available
Test method with @NullAndEmptySource to handle null and empty strings
Preconditions (2)
Step 1: Create a parameterized test method annotated with @ParameterizedTest
Step 2: Add @NullAndEmptySource annotation to provide null and empty string inputs
Step 3: Inside the test method, receive a String parameter
Step 4: Assert that the input is either null or empty
Step 5: Run the test
✅ Expected Result: The test runs twice: once with null input and once with empty string input, both passing the assertion
Automation Requirements - JUnit 5
Assertions Needed:
Assert that the input string is null or empty
Best Practices:
Use @ParameterizedTest with @NullAndEmptySource for concise null and empty input testing
Use Assertions.assertTrue with clear condition
Keep test method names descriptive
Automated Solution
JUnit
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.

Common Mistakes - 3 Pitfalls
Using @ValueSource with empty string but forgetting to test null
Not checking for null before calling isEmpty()
{'mistake': 'Using assertEquals("", input) to check empty but not null', 'why_bad': 'This assertion fails when input is null, missing the null test case.', 'correct_approach': 'Use assertTrue(input == null || input.isEmpty()) to cover both cases.'}
Bonus Challenge

Now add data-driven testing with @ValueSource to test additional strings along with null and empty

Show Hint