java - 访问 TestRule 中的自定义注释

标签 java spring junit annotations

前言:

我有以下注释和 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 中的注释?

最佳答案

您的申请不正确。

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

// 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
       *
       */
}

关于java - 访问 TestRule 中的自定义注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40674313/

相关文章:

testing - grails - 功能测试不会运行,即使是在 Intellij 中?

Java 代码组织 : Where to keep instance of static class

java - android - 在 webview 应用程序中打开外部链接

java - 可参数化的 JSR-303 验证值

java - spring-kafka监听并发

java - 比较java单元文本中的Xml,忽略节点中的属性

java - 将不同的图标分配给 JTree 中的不同节点

java - 将 Observable 添加到 Observable<Collection<Class>> 中

java - Spring - 扫描特定的 jar 文件

java - JUnit测试综合方法