In JUnit 5 Jupiter, you can create parameterized tests with two or more arguments using the @ParameterizedTest
and @MethodSource
annotations. To create a parameterized test with two arguments, follow these steps:
Create a test class and a static method that provides the test arguments. This method should return a Stream<Arguments>
where each Arguments
object represents a set of test arguments.
Annotate the test method with @ParameterizedTest
.
Annotate the test method's parameter(s) with @MethodSource
and specify the name of the static method that provides the test arguments.
Write your test logic inside the test method, using the provided arguments.
Here's an example of a parameterized test with two arguments:
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.Arguments; import org.junit.jupiter.params.provider.MethodSource; public class CalculatorTest { // Step 1: Define a static method to provide test arguments static Stream<Arguments> addTestArguments() { return Stream.of( Arguments.of(2, 3, 5), // (operand1, operand2, expected result) Arguments.of(0, 0, 0), Arguments.of(-1, 1, 0), Arguments.of(-1, -1, -2) ); } // Step 2: Annotate the test method with @ParameterizedTest @ParameterizedTest // Step 3: Annotate the test method's parameters with @MethodSource @MethodSource("addTestArguments") void testAdd(int operand1, int operand2, int expectedResult) { // Step 4: Write your test logic using the provided arguments Calculator calculator = new Calculator(); int result = calculator.add(operand1, operand2); assertEquals(expectedResult, result, "Incorrect addition result"); } }
In this example:
We have a Calculator
class with an add
method that we want to test.
We define a static method addTestArguments
that provides a stream of Arguments
objects. Each Arguments
object contains two operands and the expected result.
The @ParameterizedTest
annotation is applied to the testAdd
method.
The @MethodSource("addTestArguments")
annotation specifies that the test arguments should be obtained from the addTestArguments
method.
Inside the testAdd
method, we use the provided arguments to perform the test and make assertions.
Now, when you run this test class, JUnit 5 will execute the testAdd
method multiple times with different sets of arguments, effectively creating parameterized tests with two arguments.
poker pty external-links wear-os first-class-functions version formgroups cakephp-3.x slash android-popupwindow