Get custom method annotation value from junit test

你离开我真会死。 提交于 2020-01-03 03:34:28

问题


I have a junit test where I'd like to use an annotation on methods to define test settings.

I have a super class of the test class where I have abstracted some processing and where I'd like to read the method annotation values.

I have seen examples of reading method annotations by looping over a class. I'm not sure this will work for what I need. How do I find which test method was called and then read those specific annotation values (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();

}

回答1:


I learned that you can access the junit method through the junit class. Then getting the annotation value is trivial.

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());
        ...
    }
}


来源:https://stackoverflow.com/questions/34098011/get-custom-method-annotation-value-from-junit-test

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!