Test isEven method with multiple integer inputs using @ValueSource
Preconditions (2)
✅ Expected Result: The test passes confirming isEven returns true for all even numbers provided
import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; public class NumberUtilsTest { // Method to test public static boolean isEven(int number) { return number % 2 == 0; } @ParameterizedTest @ValueSource(ints = {2, 4, 6, 8, 10}) void testIsEvenWithEvenNumbers(int number) { assertTrue(isEven(number), "Number " + number + " should be even"); } }
The test class NumberUtilsTest contains the method isEven which returns true if the number is even.
The test method testIsEvenWithEvenNumbers is annotated with @ParameterizedTest and @ValueSource to run the test multiple times with different integer inputs.
For each input, the test asserts that isEven returns true, confirming the method works correctly for even numbers.
This approach avoids writing multiple test methods for each input and keeps tests clean and readable.
Now add data-driven testing with 3 different inputs including even and odd numbers and verify isEven returns correct boolean
@ValueSource in JUnit tests?@ValueSource with integers in JUnit 5?ints.@ValueSource(ints = {1, 2, 3}), which is the correct syntax.@ParameterizedTest
@ValueSource(strings = {"apple", "banana"})
void testLength(String fruit) {
System.out.println(fruit.length());
}@ValueSource:@ParameterizedTest
@ValueSource(strings = {"test", null})
void testNotNull(String input) {
assertNotNull(input);
}@ValueSource to test a method that accepts both int and long values?Pass the test and this pattern moves unknown