11

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
}
Maciej Kowalski
  • 25,605
  • 12
  • 54
  • 63
telebog
  • 1,706
  • 5
  • 25
  • 34

1 Answers1

14

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.

Maciej Kowalski
  • 25,605
  • 12
  • 54
  • 63