How to reuse JUnit Jupiter @MethodSource for multiple parameterized tests How to reuse JUnit Jupiter @MethodSource for multiple parameterized tests selenium selenium

How to reuse JUnit Jupiter @MethodSource for multiple parameterized tests


The easiest way is to reference a static factory method via its fully qualified method name -- for example, @MethodSource("example.Testing#text()").

To simplify matters even further, you can introduce a custom composed annotation that combines the configuration for @ParameterizedTest and @MethodSource like this:

import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;import org.junit.jupiter.params.ParameterizedTest;import org.junit.jupiter.params.provider.MethodSource;@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)@ParameterizedTest@MethodSource("example.Testing#text()")public @interface ParameterizedTextTest {}

You can then reuse that like this:

package example;import org.junit.jupiter.api.Nested;class Testing {    static String[] text() {        return new String[] { "A", "B" };    }    @Nested    class NestedTesting {        @ParameterizedTextTest        void testA(String text) {            System.out.println(text);        }        @ParameterizedTextTest        void testB(String text) {            System.out.println(text);        }    }}

Happy testing!