java - JUnit getAnnotation 返回 null

标签 java junit junit4

我想运行一个简单的规则,如果它有特定的注释,它将尝试重新运行测试。具体来说,它将尝试根据用户的需要多次重新运行测试,方法是从 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/

相关文章:

java - 如何制作要运行的测试的 junit 白名单

Java JUnit4 : Make simple assertEquals Test pass

java - JNA 不支持 C++11?

java - 通过 unicode 添加表情符号 react 不起作用

java - 多选 ListView 和 SharedPreferences

java.lang.NoSuchMethodError : javaxservlet. http.HttpServletRequest.isAsyncStarted()Z

java - 包含Thread.sleep的JUnit测试方法

java - 是否有集成 Spring-MVC 和 Spring-Data-JPA 的示例 Web 项目?

java - JUnit Jupiter (JUnit5) 中的参数化测试执行

java - 验证私有(private)构造函数未使用 JMockit 调用/调用