Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Junit5 @MethodSource passing parameter to the method

Tags:

junit5

I'm looking for how to pass a parameter into a metod that use the @MethodSource annotatio in Junit5

For example I need to invoke @MethodSource annotation and passing a value into the method "MyFactoryMethod". It is possible? Sometings like this:

@ParameterizedTest
@MethodSource("MyFactoryMethod(10)")
void testWithMethodSource(int argument) {
    assertNotEquals(9, argument);
}

static IntStream MyFactoryMethod(String var) {
    return IntStream.range(0, var);
}

Thanks in advance

like image 332
Alex Avatar asked Apr 01 '26 10:04

Alex


1 Answers

Unfortunately, it's not supported, at least in Jupiter JUnit v.5.8.2.

You are allowed to provide names of methods within the test class as well as external classes. Note that methods in external classes must be referenced by fully qualified method name - com.package.Class#methodName.

Example:

Referring to a method within the test class @MethodSource("getParams")

External methods @MethodSource("com.app.test.ArgumentsProvider#getArgs")

There is an option to implement a custom annotation of your own, if nothing else suits you maybe consider that.

Example of how to implement such annotation

like image 51
zoobiE- Avatar answered Apr 23 '26 03:04

zoobiE-