0
0
JUnittesting~10 mins

@NullAndEmptySource in JUnit - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test uses the @NullAndEmptySource annotation in JUnit to run the same test method twice: once with a null input and once with an empty string. It verifies that the method handles both cases correctly by returning false.

Test Code - JUnit 5
JUnit
import static org.junit.jupiter.api.Assertions.assertFalse;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.NullAndEmptySource;

public class InputValidatorTest {

    @ParameterizedTest
    @NullAndEmptySource
    void testIsValidInputWithNullAndEmpty(String input) {
        InputValidator validator = new InputValidator();
        boolean result = validator.isValidInput(input);
        assertFalse(result, "Input should be invalid for null or empty string");
    }
}

class InputValidator {
    public boolean isValidInput(String input) {
        return input != null && !input.isEmpty();
    }
}
Execution Trace - 4 Steps
StepActionSystem StateAssertionResult
1Test startsJUnit test runner initializes the test class InputValidatorTest-PASS
2Runs parameterized test with input = nullInputValidator instance created; input parameter is nullassertFalse(result) where result = isValidInput(null)PASS
3Runs parameterized test with input = "" (empty string)InputValidator instance created; input parameter is empty stringassertFalse(result) where result = isValidInput("")PASS
4Test endsAll parameterized test cases executed-PASS
Failure Scenario
Failing Condition: The isValidInput method returns true for null or empty string inputs
Execution Trace Quiz - 3 Questions
Test your understanding
What inputs does the @NullAndEmptySource annotation provide to the test method?
Anull and empty string
Bnull and whitespace string
Cempty string and whitespace string
Dnull only
Key Result
Using @NullAndEmptySource in JUnit parameterized tests helps verify that methods correctly handle null and empty inputs, which are common edge cases that can cause bugs if not tested.