【问题标题】:Access custom annotation in a TestRule访问 TestRule 中的自定义注释
【发布时间】:2017-04-02 03:23:24
【问题描述】:

前言:

我有以下注释和 junit 测试的规则初始化部分。 目标是使用不同的配置并使测试尽可能简单易用。

// Annotation
@Retention(RetentionPolicy.RUNTIME)
public @interface ConnectionParams {
    public String username();
    public String password() default "";
}

// Part of the test
@ConnectionParams(username = "john")
@Rule
public ConnectionTestRule ctr1 = new ConnectionTestRule();

@ConnectionParams(username = "doe", password = "secret")
@Rule
public ConnectionTestRule ctr2 = new ConnectionTestRule();

现在我想访问下面TestRule中的注解参数,但是没有找到任何注解。

public class ConnectionTestRule implements TestRule {
    public Statement apply(Statement arg0, Description arg1) {
        if (this.getClass().isAnnotationPresent(ConnectionParams.class)) {
            ... // do stuff
        }
    }
}

如何访问 TestRule 中的注释?

【问题讨论】:

    标签: java spring junit annotations


    【解决方案1】:

    您的申请不正确。

    在类级别应用自定义注释,而不是按照你已经完成的方式。

    // Apply on class instead
    @ConnectionParams(username = "john")
    public class ConnectionTestRule {....
    

    那么你的代码应该可以工作了,

    public class ConnectionTestRule implements TestRule {
        public Statement apply(Statement arg0, Description arg1) {
          //get annotation from current (this) class
          if (this.getClass().isAnnotationPresent(ConnectionParams.class)) {
            ... // do stuff
          }
        }
    }
    

    编辑:更新问题后。

    您需要首先使用反射获取该字段,以便找到您创建的每个 ConnectionTestRule 对象并从中获取您的注释以获取所需的配置。

    for(Field field : class_in_which_object_created.getDeclaredFields()){
          Class type = field.getType();
          String name = field.getName();
          //it will get annotations from each of your 
          //public ConnectionTestRule ctr1 = new ConnectionTestRule();
          //public ConnectionTestRule ctr2 = new ConnectionTestRule();
          Annotation[] annotations = field.getDeclaredAnnotations();
          /*
           *
           *once you get your @ConnectionParams then pass it respective tests
           *
           */
    }
    

    【讨论】:

    • 我更新了问题,我的目标是用不同的配置运行测试
    • 我已经更新了答案。您需要首先从您的对象/字段中找到注释,然后从中获取注释,最后将配置传递给您的测试
    • TestRule 不知道它将在哪里使用,因此您建议的“class_in_which_object_created.getDeclaredFields()”将无法正常工作。
    • 你不知道这将在哪个类中创建? @ConnectionParams(username = "john") @Rule public ConnectionTestRule ctr1 = new ConnectionTestRule();
    • 没错,我不知道谁会使用规则建立连接。
    猜你喜欢
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 2015-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多