0
0
JUnittesting~15 mins

@ParameterizedTest annotation in JUnit - Build an Automation Script

Choose your learning style9 modes available
Automate parameterized test for checking if numbers are even
Preconditions (2)
Step 1: Create a parameterized test method using @ParameterizedTest
Step 2: Use @ValueSource to provide integers: 2, 4, 6, 8, 10
Step 3: For each input number, call the method that checks if the number is even
Step 4: Assert that the method returns true for each input
✅ Expected Result: The test passes for all input numbers confirming they are even
Automation Requirements - JUnit 5
Assertions Needed:
Assert that the method returns true for each input number
Best Practices:
Use @ParameterizedTest with @ValueSource for simple input values
Keep test method names descriptive
Use assertions from org.junit.jupiter.api.Assertions
Avoid hardcoding values inside the test method body
Automated Solution
JUnit
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.

Common Mistakes - 4 Pitfalls
Using @Test instead of @ParameterizedTest for parameterized inputs
Hardcoding input values inside the test method instead of using @ValueSource
Not importing the correct Assertions class
Not providing a descriptive assertion message
Bonus Challenge

Now add data-driven testing with 3 different inputs including even and odd numbers, and assert the expected boolean result for each.

Show Hint