Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

junit5

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?

like image 910
Niraj Sonawane Avatar asked Dec 30 '18 06:12

Niraj Sonawane


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);
}
like image 97
Niraj Sonawane Avatar answered Nov 17 '22 17:11

Niraj Sonawane