我想运行一个简单的规则,如果它有特定的注释,它将尝试重新运行测试。具体来说,它将尝试根据用户的需要多次重新运行测试,方法是从 cusotm 读取 attempts int注释。
这是我创建的 cusotm 注释: 导入 java.lang.annotation.ElementType; 导入java.lang.annotation.Target;
@Target(ElementType.METHOD)
public @interface Retry {
int tries();
}
这是我创建的自定义规则:
public class RetryRule implements TestRule {
@Override
public Statement apply(final Statement base, final Description description) {
if( description.getAnnotation(Retry.class) == null ) {
System.out.println("Hm...");
return base;
}
int tries = description.getAnnotation(Retry.class).tries();
return new Statement() {
@Override
public void evaluate() throws Throwable {
while(true) {
int i = 1 ;
try {
i++;
base.evaluate();
return ;
} catch (AssertionError ex) {
if( i >= tries ) {
return ;
}
}
}
}
};
}
}
问题是,每当我使用自定义注释和自定义规则运行测试时,它总是只运行一次。我检查过,并且 getAnnotation(....) 在任何情况下都始终返回 null — 如果 cusotm 注释是指定或没有。
最佳答案
您的注释不会保留到运行时。
使用@Retention(RetentionPolicy.RUNTIME)
关于java - JUnit getAnnotation 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55849723/