从junit测试获取自定义方法注释值 [英] Get custom method annotation value from junit test
问题描述
我有一个junit测试,我想在方法上使用注释来定义测试设置.
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.
我已经看到了通过遍历一个类来读取方法注释的示例.我不确定这是否可以满足我的需求.如何找到调用了哪种测试方法,然后读取那些特定的注释值(TrialMethod.name)?
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();
}
推荐答案
我了解到可以通过junit类访问junit方法.然后获得注释值是微不足道的.
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());
...
}
}
这篇关于从junit测试获取自定义方法注释值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!