如何将 JUnit 注解组合成自定义注解?
How to combine JUnit annotations into a custom annotation?
(使用 OpenJDK-13 和 JUnit5-Jupiter)
问题是我的每个单元测试都使用了一个不小的 JUnit 注释系统,像这样:
@ParameterizedTest
@MethodSource("myorg.ccrtest.testlogic.DataProviders#standardDataProvider")
@Tags({@Tag("ccr"), @Tag("standard")})
这使得测试编写有点乏味,测试代码有点长,当然,当需要更改时,这是一件苦差事!
想知道我是否可以创建自己的 JUnit 注释:@CcrStandardTest
,这意味着上面的所有注释?
我也尝试在 class 定义中向上移动注释(希望它们随后适用于 class 的所有方法),但编译器说不:“@ParameterizedTest 不适用键入
你可以做一个composed annotation:
JUnit Jupiter annotations can be used as meta-annotations. That means that you can define your own composed annotation that will automatically inherit the semantics of its meta-annotations.
例如:
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.ANNOTATION_TYPE, ElementType.METHOD})
@ParameterizedTest
@MethodSource("myorg.ccrtest.testlogic.DataProviders#standardDataProvider")
@Tag("ccr")
@Tag("standard")
public @interface CcrStandardTest {}
然后您可以将组合注释放在您的测试方法上:
@CcrStandardTest
void testFoo(/* necessary parameters */) {
// perform test
}
(使用 OpenJDK-13 和 JUnit5-Jupiter)
问题是我的每个单元测试都使用了一个不小的 JUnit 注释系统,像这样:
@ParameterizedTest
@MethodSource("myorg.ccrtest.testlogic.DataProviders#standardDataProvider")
@Tags({@Tag("ccr"), @Tag("standard")})
这使得测试编写有点乏味,测试代码有点长,当然,当需要更改时,这是一件苦差事!
想知道我是否可以创建自己的 JUnit 注释:@CcrStandardTest
,这意味着上面的所有注释?
我也尝试在 class 定义中向上移动注释(希望它们随后适用于 class 的所有方法),但编译器说不:“@ParameterizedTest 不适用键入
你可以做一个composed annotation:
JUnit Jupiter annotations can be used as meta-annotations. That means that you can define your own composed annotation that will automatically inherit the semantics of its meta-annotations.
例如:
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.ANNOTATION_TYPE, ElementType.METHOD})
@ParameterizedTest
@MethodSource("myorg.ccrtest.testlogic.DataProviders#standardDataProvider")
@Tag("ccr")
@Tag("standard")
public @interface CcrStandardTest {}
然后您可以将组合注释放在您的测试方法上:
@CcrStandardTest
void testFoo(/* necessary parameters */) {
// perform test
}