0
0
JUnittesting~15 mins

@NullSource and @EmptySource in JUnit - Build an Automation Script

Choose your learning style9 modes available
Test method behavior with null and empty inputs using @NullSource and @EmptySource
Preconditions (2)
Step 1: Create a parameterized test method using @NullSource and @EmptySource annotations
Step 2: Run the test method with null input from @NullSource
Step 3: Run the test method with empty string input from @EmptySource
Step 4: Verify that the method under test returns false for both null and empty string inputs
✅ Expected Result: The test method runs twice: once with null and once with empty string, and both times the assertion verifies the method returns false
Automation Requirements - JUnit 5
Assertions Needed:
Assert that the method returns false when input is null
Assert that the method returns false when input is empty string
Best Practices:
Use @ParameterizedTest with @NullSource and @EmptySource for concise input coverage
Use descriptive test method names
Keep assertions clear and focused
Automated Solution
JUnit
import static org.junit.jupiter.api.Assertions.assertFalse;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EmptySource;
import org.junit.jupiter.params.provider.NullSource;

public class StringValidatorTest {

    // Method under test: returns true if input is not null and not empty
    public boolean isValid(String input) {
        return input != null && !input.isEmpty();
    }

    @ParameterizedTest
    @NullSource
    @EmptySource
    void testIsValidWithNullAndEmpty(String input) {
        assertFalse(isValid(input), "Expected isValid to return false for input: " + input);
    }
}

This test class defines a method isValid that returns true only if the input string is not null and not empty.

The test method testIsValidWithNullAndEmpty is annotated with @ParameterizedTest, @NullSource, and @EmptySource. This means the test will run twice: once with null and once with an empty string ("").

Inside the test, assertFalse checks that isValid returns false for both inputs, which matches the expected behavior.

This approach is clean and concise, covering two important edge cases without writing separate tests.

Common Mistakes - 3 Pitfalls
Not using @ParameterizedTest with @NullSource and @EmptySource together
Using @ValueSource with empty string instead of @EmptySource
Not asserting the expected result for null or empty inputs
Bonus Challenge

Now add data-driven testing with 3 different non-empty strings that should return true

Show Hint