从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屋!