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.