如何重用 JUnit Jupiter @MethodSource 进行多个参数化测试
How to reuse JUnit Jupiter @MethodSource for multiple parameterized tests
假设我有以下代码:
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);
}
}
}
当我 运行 这个时,我得到:
No tests found with test runner 'JUnit 5'.
我怎样才能让它工作?我是 Java 的初学者,所以我可能忘记了一些明显的东西
最简单的方法是通过完全限定的方法名称引用static
工厂方法——例如,@MethodSource("example.Testing#text()")
.
为了进一步简化问题,您可以引入一个自定义 组合注释 ,它结合了 @ParameterizedTest
和 @MethodSource
的配置,如下所示:
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 {
}
然后您可以像这样重复使用它:
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);
}
}
}
测试愉快!
假设我有以下代码:
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);
}
}
}
当我 运行 这个时,我得到:
No tests found with test runner 'JUnit 5'.
我怎样才能让它工作?我是 Java 的初学者,所以我可能忘记了一些明显的东西
最简单的方法是通过完全限定的方法名称引用static
工厂方法——例如,@MethodSource("example.Testing#text()")
.
为了进一步简化问题,您可以引入一个自定义 组合注释 ,它结合了 @ParameterizedTest
和 @MethodSource
的配置,如下所示:
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 {
}
然后您可以像这样重复使用它:
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);
}
}
}
测试愉快!