且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

JUnit5-Jupiter:组合(="meta")注释无法解析为注释定义

更新时间: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

  • RetentionPolicy.CLASS

    注释由编译器记录在类文件中,但VM不必在运行时保留. 这是默认行为. [添加了重点]

  • RetentionPolicy.RUNTIME

  • 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.