JUnit getAnnotation returns 空
JUnit getAnnotation returns null
我想要 运行 一个简单的规则,它会尝试重新运行 测试,如果它有一个特定的 annotation.Specifically,它会尝试重新运行通过从 cusotm annotationt 中读取 tries 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 ;
}
}
}
}
};
}
}
问题是每当我 运行 使用自定义注释和自定义规则进行测试时,它总是 运行 仅 once.I 检查,并且 getAnnotation(... .) returns 在任何情况下始终为 null — 如果指定或未指定 cusotm 注释。
您的注释不会保留到运行时。
使用 @Retention(RetentionPolicy.RUNTIME)
我想要 运行 一个简单的规则,它会尝试重新运行 测试,如果它有一个特定的 annotation.Specifically,它会尝试重新运行通过从 cusotm annotationt 中读取 tries 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 ;
}
}
}
}
};
}
}
问题是每当我 运行 使用自定义注释和自定义规则进行测试时,它总是 运行 仅 once.I 检查,并且 getAnnotation(... .) returns 在任何情况下始终为 null — 如果指定或未指定 cusotm 注释。
您的注释不会保留到运行时。
使用 @Retention(RetentionPolicy.RUNTIME)