java - 单元测试时未找到自定义注释
问题描述
说我有这样的注释:
@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;
}
};
如果我在实例化时覆盖某些方法,实例是否可能会丢失所有注释?
解决方案
由于exampleCommandToExample
ref 表示匿名类的实例,因此调用会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
将使注释对匿名实现可见。
推荐阅读
- sql-server - 计算两个“P”状态之间的“F”状态
- xml - odoo 从库存移动中编写发票
- javascript - Js中文档对象的意外行为
- flutter - 颤振类型'String'不是'index'的'int'类型的子类型
- javascript - 如何替换具有特定类的元素的类?
- unity3d - 如何使用统一引擎处理体素图形
- git - 将启用 LFS 的本地 Git 存储库推送到空的 Azure Devops 失败
- python - 使用字典中的值过滤 Spark DataFrame
- powershell - powershell 脚本根据文件名中的特定文本对文件进行分组
- sql - PostgreSQL,Window函数使用问题(附具体例子)