0
0
JUnittesting~15 mins

@ValueSource for simple values in JUnit - Build an Automation Script

Choose your learning style9 modes available
Test isEven method with multiple integer inputs using @ValueSource
Preconditions (2)
Step 1: Create a parameterized test method using @ValueSource with integers: 2, 4, 6, 8, 10
Step 2: For each integer input, call isEven(number)
Step 3: Verify that the method returns true for all inputs
✅ Expected Result: The test passes confirming isEven returns true for all even numbers provided
Automation Requirements - JUnit 5
Assertions Needed:
Assert that isEven returns true for each input value
Best Practices:
Use @ParameterizedTest with @ValueSource for simple input values
Use descriptive test method names
Keep test methods focused on one behavior
Use assertions from org.junit.jupiter.api.Assertions
Automated Solution
JUnit
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.

Common Mistakes - 3 Pitfalls
Using @Test instead of @ParameterizedTest for multiple inputs
Passing values as strings instead of correct type in @ValueSource
Not asserting the expected result inside the test method
Bonus Challenge

Now add data-driven testing with 3 different inputs including even and odd numbers and verify isEven returns correct boolean

Show Hint