gpt4 book ai didi

java - 从junit测试中获取自定义方法注释值

转载 作者:太空宇宙 更新时间:2023-11-04 13:09:40 25 4
gpt4 key购买 nike

我有一个 junit 测试,我想在方法上使用注释来定义测试设置。

我有一个测试类的父类(super class),我在其中抽象了一些处理,并且我想在其中读取方法注释值。

我见过通过循环类来读取方法注释的示例。我不确定这是否能满足我的需要。如何找到调用了哪个测试方法,然后读取那些特定的注释值(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());
...
}
}

关于java - 从junit测试中获取自定义方法注释值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34098011/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com