首页 > 解决方案 > 单元测试时未找到自定义注释

问题描述

说我有这样的注释:

@Retention(RetentionPolicy.RUNTIME)
public @interface AutoConvert {
    boolean enabled() default true;
}

和用它注释的类:

@AutoConvert
public class ExampleCommandToExample extends BaseConverter{}

在超类上,我正在执行以下操作:

public void convert(){
  Annotation annotation = (AutoConvert) this.getClass().getAnnotation(AutoConvert.class);
}

运行时一切正常!正在找到并正确设置注释!

但!使用 JUnit 对 convert 方法进行单元测试时:this.getClass().getAnnotation(AutoConvert.class) 始终返回 null。

测试看起来像这样:

@Test
public void convertTest(){
    //when
    exampleCommandToExample.convert();
}

运行单元测试时是否没有通过反射找到自定义注释?有人给我答案吗?我真的很感激。

先感谢您。

编辑: 好吧,它似乎是基于那种 intatiation ......我做了以下事情:

exampleCommandToExample = new ExampleCommandToExample() {
    @Override
    public Type overideSomeMethod() {
        return type;
    }
};

如果我在实例化时覆盖某些方法,实例是否可能会丢失所有注释?

标签: javareflectionjunitannotations

解决方案


由于exampleCommandToExampleref 表示匿名类的实例,因此调用会this.getClass().getAnnotation(AutoConvert.class)收集其级别的注释和所有继承的注释。

然而,@AutoConvert在这个匿名实现的例子中,没有继承,这就是为什么getAnnotation返回null,这完全对应于Java API中声明的行为:

如果存在这样的注释,则返回此元素的指定类型的注释,否则返回 null。

要解决此问题,只需添加

import java.lang.annotation.Inherited;

@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface AutoConvert { /* no changes */ }

@Inherited将使注释对匿名实现可见。


推荐阅读