Automate parameterized test for checking if numbers are even
Preconditions (2)
✅ Expected Result: The test passes for all input numbers confirming they are even
import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import static org.junit.jupiter.api.Assertions.assertTrue; public class NumberUtilsTest { 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"); } }
This test class defines a static method isEven that returns true if a 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 number, the test calls isEven and asserts the result is true using assertTrue. The assertion message helps identify which input failed if any.
This approach avoids repeating similar test code and clearly shows how parameterized tests work in JUnit 5.
Now add data-driven testing with 3 different inputs including even and odd numbers, and assert the expected boolean result for each.
@ParameterizedTest annotation in JUnit?@ParameterizedTest using @ValueSource?@ParameterizedTest
@ValueSource(strings = {"apple", "banana"})
void testLength(String fruit) {
System.out.println(fruit.length());
}@ParameterizedTest
@ValueSource(ints = {1, 2, 3})
void testIsPositive(String number) {
assertTrue(Integer.parseInt(number) > 0);
}@ParameterizedTest with multiple inputs including 0, -2, and 3. Which of the following test method signatures and annotations correctly achieve this?Pass the test and this pattern moves unknown