Search code examples
javaunit-testingtestingjunitjunit5

JUnit5 parameterized test with multiple method source


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
}

Solution

  • The @MethodSource can accept as many factory methods as you like according to its Javadocs:

    String[] value

    The names of factory methods within the test class or in external classes to use as sources for arguments.

    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 that's a detail of your implementation.