How to use @MethodSource defined in other class in JUnit 5

Viewed 3723

Is there any way to use @MethodSource to use a method defined in other class ?

e.g: Below code works, as the stringProvider method is defined in same class.

@ParameterizedTest
@MethodSource("stringProvider")
void methodSourceFromOtherClass(String word) {
    System.out.println(word);
    assertNotNull(word);
}

public static Stream<Arguments> stringProvider() {
    return Stream.of(
            Arguments.of("Values"),
            Arguments.of("From"),
            Arguments.of("MethodSource"));      
}

I have some utility classes, that provides test data. How can I use method from external classes in @methodSource?

1 Answers

Syntax for referring methods from external classes

@MethodSource("fullyQualifiedClassName#methodName")

e.g.

@ParameterizedTest
@MethodSource("com.niraj.DataProvider#stringProvider")
void methodSourceFromOtherClass(String word) {
    System.out.println(word);
    assertNotNull(word);
}
Related