import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.Arguments;
import java.util.stream.Stream;
public class CalculatorTest {
static Stream<Arguments> provideAddInputs() {
return Stream.of(
Arguments.of(1, 2, 3),
Arguments.of(5, 7, 12),
Arguments.of(-1, 1, 0)
);
}
@ParameterizedTest
@MethodSource("provideAddInputs")
void testAdd(int a, int b, int expectedSum) {
Calculator calculator = new Calculator();
int result = calculator.add(a, b);
assertEquals(expectedSum, result, () -> "Sum of " + a + " and " + b + " should be " + expectedSum);
}
}
class Calculator {
int add(int x, int y) {
return x + y;
}
}The static method provideAddInputs is the factory method that returns a Stream<Arguments>. Each Arguments.of() call provides one set of parameters for the test.
The test method testAdd is annotated with @ParameterizedTest and @MethodSource referencing the factory method by name. It accepts parameters matching the factory method's arguments.
Inside the test, we create a Calculator instance and call the add method with the parameters. Then we assert the result equals the expected sum.
This setup runs the test three times, once per data set, verifying the addition logic for different inputs.