2016-11-18 169 views
0

前言:在TestRule中访问自定义注释

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

回答

0

您的申请不正确。

在课堂级别上应用自定义注释,而不是按照您所做的方式应用自定义注释。

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

我更新了这个问题,我的目标是,运行不同配置的测试 –

+0

我已经更新了答案。您需要首先从您的对象/字段中找到注释,然后从中获取注释,并最终将配置传递给您的测试。 – ScanQR

+0

TestRule不知道它将在何处使用,因此您所建议的“class_in_which_object_created.getDeclaredFields()”将不起作用出。 –