5

Let's say I have the following code:

class Testing {

    String[] text() {
        String[] text = { "A", "B" };
        return text;

    }

    @Nested
    class NestedTesting {

        @ParameterizedTest
        @MethodSource("text")
        void A(String text) {

            System.out.println(text);

        }

        @ParameterizedTest
        @MethodSource("text")
        void B(String text) {

            System.out.println(text);

        }
    }
}

When I run this, I get:

No tests found with test runner 'JUnit 5'.

How can I get this to work? I'm a beginner in Java, so I'm probably forgetting something obvious

1 Answer 1

10

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!

Sign up to request clarification or add additional context in comments.

1 Comment

I think the @MethodSource would make a lot of sense with value() == methodName() and an optional className(). Would be a lot more intuitive.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.