如何将 JUnit 注释组合成自定义注释? [英] How to combine JUnit annotations into a custom annotation?
问题描述
(使用 OpenJDK-13 和 JUnit5-Jupiter)
(Using OpenJDK-13 and JUnit5-Jupiter)
问题是我的单元测试每个都使用了一个不小的 JUnit 注释系统,如下所示:
The problem is that my unit tests each make use of a not-small JUnit annotation system, something like this:
@ParameterizedTest
@MethodSource("myorg.ccrtest.testlogic.DataProviders#standardDataProvider")
@Tags({@Tag("ccr"), @Tag("standard")})
这使得测试编写有点乏味,测试代码有点长,当然,当需要更改时,这是一件苦差事!
This makes test authoring a little tedious, test code a little long and of course, when a change is needed, it's a chore!
想知道我是否可以创建自己的 JUnit 注释:@CcrStandardTest
,这意味着上面的所有注释?
Was wondering if I could create my own JUnit annotation: @CcrStandardTest
, which would imply all of the annotations above?
我还尝试将类定义中的注解上移(希望它们随后适用于类的所有方法),但编译器说不:@ParameterizedTest 不适用于类型"
I also tried shifting the annotations up in the class definition (hoping they would then apply to all methods of the class), but the compiler says no: "@ParameterizedTest is not applicable to type"
推荐答案
您可以制作一个 组合注释:
JUnit Jupiter 注释可以用作元注释.这意味着您可以定义自己的组合注解,该注解将自动继承元注解的语义.
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 {}
然后您将组合注释放在您的测试方法上:
You would then place the composed annotation on your test method:
@CcrStandardTest
void testFoo(/* necessary parameters */) {
// perform test
}
这篇关于如何将 JUnit 注释组合成自定义注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!