I have 4 tests each with its own method source but the only difference between them is one parameter, in each method I init the mocks in different way. Is there a way that I can pass multiple method source?
Example:
@ParameterizedTest
@MethodSource("mSource1")
public void testM1(MyMock m1, MyMock m2) {
callMut(m1, m2, ENUM.VAL1);
//same assertion
}
@ParameterizedTest
@MethodSource("mSource2")
public void testM2(MyMock m1, MyMock m2) {
callMut(m1, m2, ENUM.VAL2);
//same assertion
}
private static Stream<Arguments> mSource1() {
when(myMock1.getX()).thenReturn("1");
//...
}
private static Stream<Arguments> mSource2() {
when(myMock1.getY()).thenReturn("1");
//...
}
I am looking for something like:
@ParameterizedTest
@MethodSource("mSource1", "mSource2")
public void testM1(MyMock m1, MyMock m2, MyEnum myEnumValue) {
callMut(m1, m2, myEnumValue);
//same assertion
}
Writing Our First Parameterized TestsAdd a new test method to our test class and ensure that this method takes a String object as a method parameter. Configure the display name of the test method. Annotate the test method with the @ParameterizedTest annotation. This annotation identifies parameterized test methods.
JUnit5 Parameterized Test helps to run the same tests multiple times with different arguments/values. They are declared just like the regular @Test method but instead of @Test annotation @ParameterizedTest is used. All supported argument sources are configured using annotations from the org.
The @CsvSource accepts an array of comma-separated values, and each array entry corresponds to a line in a CSV file. This source takes one array entry each time, splits it by comma and passes each array to the annotated test method as separate parameters.
@ParameterizedTest. Parameterized tests make it possible to run a test multiple times with different arguments. They are declared just like regular @Test methods but use the @ParameterizedTest annotation instead.
The @MethodSource
can accept as many factory methods as you like according to javadocs:
public abstract String[] value
The names of the test class methods to use as sources for arguments; must not be empty.
So simply put those inside curly braces and make sure they return an enum value also:
@MethodSource({"mSource1", "mSource2"})
As I see it though, you may need to move the when().then() set-up to the test itself, but thats a detail of your impl.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With