Test Overview
This test checks a method that processes strings. It verifies the method handles null and empty string inputs correctly by using @NullSource and @EmptySource annotations in JUnit.
This test checks a method that processes strings. It verifies the method handles null and empty string inputs correctly by using @NullSource and @EmptySource annotations in JUnit.
import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.NullSource; import org.junit.jupiter.params.provider.EmptySource; import static org.junit.jupiter.api.Assertions.*; public class StringProcessorTest { @ParameterizedTest @NullSource @EmptySource void testProcessStringHandlesNullAndEmpty(String input) { StringProcessor processor = new StringProcessor(); String result = processor.process(input); assertEquals("default", result); } } class StringProcessor { public String process(String input) { if (input == null || input.isEmpty()) { return "default"; } return input.trim(); } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts with input = null from @NullSource | Test environment initialized, no UI involved | Check if process(null) returns "default" | PASS |
| 2 | Test runs with input = "" (empty string) from @EmptySource | Test environment ready for next input | Check if process("") returns "default" | PASS |
@NullSource annotation in JUnit parameterized tests?@NullSource role@NullSource is used to supply a null value as input to a parameterized test method.@EmptySource provides empty values like empty strings or collections, not null. Other options do not match @NullSource behavior.@NullSource = null input [OK]@NullSource and @EmptySource together in a JUnit 5 parameterized test?@NullSource and @EmptySource must be placed above the test method along with @ParameterizedTest.String input) to receive values from sources.@ParameterizedTest
@NullSource
@EmptySource
void testInput(String input) {
System.out.println(input == null ? "null" : "'" + input + "'");
}@NullSource provides a null input, and @EmptySource provides an empty string input.@ParameterizedTest
@NullSource
@EmptySource
void test(String input) {
assertNotNull(input);
}@NullSource provides a null input, and @EmptySource provides an empty string input.assertNotNull(input) will fail when input is null, causing an AssertionError.@NullSource), empty string (from @EmptySource), and a non-empty string (from @ValueSource).Pass the test and this pattern moves unknown