0
0
JUnittesting~15 mins

Multiple parameter types in JUnit - Build an Automation Script

Choose your learning style9 modes available
Verify addition method with multiple parameter types
Preconditions (1)
Step 1: Call the add method with integer 5 and double 3.2
Step 2: Call the add method with integer -1 and double 0.0
Step 3: Call the add method with integer 0 and double -2.5
✅ Expected Result: The add method returns the correct sum as double for each pair of inputs: 8.2, -1.0, and -2.5 respectively.
Automation Requirements - JUnit 5
Assertions Needed:
Assert that the returned value is equal to the expected sum with a small delta for floating point comparison.
Best Practices:
Use @ParameterizedTest with @MethodSource to supply multiple parameter types
Use descriptive test method names
Use assertions with delta for double comparison
Keep test code clean and readable
Automated Solution
JUnit
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;

public class CalculatorTest {

    static class Calculator {
        public double add(int a, double b) {
            return a + b;
        }
    }

    private static Stream<org.junit.jupiter.params.provider.Arguments> provideParameters() {
        return Stream.of(
            org.junit.jupiter.params.provider.Arguments.of(5, 3.2, 8.2),
            org.junit.jupiter.params.provider.Arguments.of(-1, 0.0, -1.0),
            org.junit.jupiter.params.provider.Arguments.of(0, -2.5, -2.5)
        );
    }

    @ParameterizedTest(name = "add({0}, {1}) = {2}")
    @MethodSource("provideParameters")
    void testAddWithMultipleParameterTypes(int a, double b, double expected) {
        Calculator calculator = new Calculator();
        double result = calculator.add(a, b);
        assertEquals(expected, result, 0.0001, "Sum should be correct");
    }
}

This test uses JUnit 5's @ParameterizedTest with @MethodSource to supply multiple sets of parameters with different types: an int and a double. The Calculator class has an add method that takes these two parameters and returns their sum as a double.

The provideParameters method returns a stream of arguments with three test cases. The test method testAddWithMultipleParameterTypes receives these parameters, calls the add method, and asserts the result is equal to the expected sum using assertEquals with a small delta to handle floating point precision.

This approach keeps the test clean, readable, and easily extendable for more cases.

Common Mistakes - 3 Pitfalls
Using @ValueSource which supports only one parameter type
Not using delta in assertEquals for double comparison
Hardcoding test data inside the test method instead of using parameterized tests
Bonus Challenge

Now add data-driven testing with 3 different inputs including zero and negative values

Show Hint