JUnit 4迁移至JUnit 5:如何获取测试注解的属性值?
JUnit 5 中获取测试注解的等价方式
在JUnit 5的Platform Launcher API中,TestIdentifier仅包含测试的元数据标识信息,并不直接持有注解数据。要获取测试方法或类上的@GradedTest注解,需要通过ExecutionEvent提供的TestDescriptor来操作,这是JUnit 4中Description.getAnnotation()的等价实现。
具体步骤:
- 在重写
executionStarted方法时,从方法参数ExecutionEvent中获取TestDescriptor实例 - 使用
TestDescriptor的findAnnotation(Class<A>)方法获取目标注解(该方法返回Optional,避免空指针) - 从获取到的注解实例中提取所需的属性(如
name、points)
示例代码:
自定义监听器实现
import org.junit.platform.launcher.listeners.SummaryGeneratingListener; import org.junit.platform.engine.TestDescriptor; import org.junit.platform.launcher.TestIdentifier; import org.junit.platform.launcher.event.ExecutionEvent; import java.util.Optional; public class GradedTestListener extends SummaryGeneratingListener { @Override public void executionStarted(ExecutionEvent event) { super.executionStarted(event); TestIdentifier testId = event.getTestIdentifier(); // 仅处理方法级测试(根据你的注解目标调整) if (testId.isTest()) { TestDescriptor testDescriptor = event.getTestDescriptor(); // 获取@GradedTest注解 Optional<GradedTest> gradedTest = testDescriptor.findAnnotation(GradedTest.class); gradedTest.ifPresent(annotation -> { String testName = annotation.name(); int testPoints = annotation.points(); // 执行你的业务逻辑,比如记录测试分数 System.out.printf("测试[%s]启动,分值:%d%n", testName, testPoints); }); } } }
确保注解的运行时可见性
要让监听器能在运行时获取到注解,必须保证@GradedTest的保留策略为RUNTIME:
import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.METHOD; @Retention(RetentionPolicy.RUNTIME) @Target(METHOD) // 如果注解用于类,改为ElementType.TYPE public @interface GradedTest { String name(); int points(); }
额外说明:
- 如果你的
@GradedTest是类级别的注解,将判断条件改为testId.isContainer()即可处理类级元数据 TestDescriptor还提供getAnnotations()方法,可获取所有注解的集合,适合需要批量处理注解的场景
内容的提问来源于stack exchange,提问作者Ellen Spertus
相关产品推荐
相关产品推荐

