簡體   English   中英

從junit測試獲取自定義方法注釋值

[英]Get custom method annotation value from junit test

我有一個junit測試,我想在方法上使用注釋來定義測試設置。

我有一個測試類的超類,其中我抽象了一些處理,並且想讀取方法注釋值。

我已經看到了通過遍歷類讀取方法注釋的示例。 我不確定這是否可以滿足我的需求。 如何找到調用了哪種測試方法,然后讀取那些特定的注釋值(TrialMethod.name)?

public class MyUTest extends Processor{

    @Test
    @TrialMethod(name = "methodToBeTested")
    public void testMethod() throws Exception {
        //assert stuff
    }

}


public class Processor extends TestCase{

    private TrialMethodModel trialMethodModel = new TrialMethodModel();

    private void setMethodNameByAnnotation() {
        Class<?> clazz = this.getClass();
        Class<TrialMethod> trialMethodClass = TrialMethod.class;

        for (Method method : clazz.getDeclaredMethods()){

            if (method.isAnnotationPresent(trialMethodClass)){
                trialMethodModel.setName(method.getAnnotation(trialMethodClass).name());
            }
        }
    }
}

@Documented
@Target(ElementType.METHOD)
@Retention(value=RetentionPolicy.RUNTIME)
public @interface TrialMethod {

    String name();

}

我了解到可以通過junit類訪問junit方法。 然后獲得注釋值是微不足道的。

private void setTrialMethodByAnnotation() {

    Class<?> clazz = this.getClass();
    Class<TrialMethod> trialMethod = TrialMethod.class;

    Method method = null;
    try {
        method = clazz.getMethod(this.getName(),null);
    } catch (SecurityException e) {
        logger.error(e.getMessage());
    } catch (NoSuchMethodException e) {
        logger.error(e.getMessage());
    }

    if(method.isAnnotationPresent(trialMethod)){
        trialMethodModel.setName(method.getAnnotation(trialMethod).name());
        ...
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM