You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 06:46:07