Reputation: 125
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
Upvotes: 5
Views: 2808
Reputation: 31177
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!
Upvotes: 10