2016-11-18 10 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 
     } 
    } 
} 

EDIT:後に更新質問。

あなたが作成した各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()"は機能しませんでる。 –

関連する問題