如何将JUnit批注组合到自定义批注中? [英] How to combine JUnit annotations into a custom annotation?

查看:188
本文介绍了如何将JUnit批注组合到自定义批注中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(使用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆