更新时间:2022-06-12 04:31:25
As you've discovered, you need to add @Retention(RUNTIME)
to your composed annotation in order for JUnit to see it. Annotations in Java have three different retention policies:
注释将被编译器丢弃.
Annotations are to be discarded by the compiler.
RetentionPolicy.CLASS
注释由编译器记录在类文件中,但VM不必在运行时保留. 这是默认行为. [添加了重点]
RetentionPolicy.RUNTIME
注释由编译器记录在类文件中,并在运行时由VM保留,以便可以通过反射方式读取.
Annotations are to be recorded in the class file by the compiler and retained by the VM at run time, so they may be read reflectively.
如上所述,如果您未明确添加@Retention(...)
,则会使用CLASS
策略.这不适用于JUnit,因为JUnit不会扫描*.class
文件(即字节码)中的注释,而是以反射方式扫描 loaded 类以找到测试方法.没有RUNTIME
保留策略,您的注释将无法反射访问,因此JUnit永远不会看到它,因此不会执行测试.
As I emphasized above, if you don't explicitly add @Retention(...)
then the CLASS
policy is used. This won't work with JUnit because JUnit doesn't scan the *.class
files (i.e. byte-code) for the annotations, it scans the loaded classes reflectively to find test methods. Without a RUNTIME
retention policy your annotation is not reflectively accessible, thus JUnit never sees it and consequently doesn't execute the test.