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

JUnit 5迁移:自定义测试注解无法被识别如何解决?

问题分析与解决方案

问题根源

spring-boot-starter-test 2.7.18默认采用JUnit Jupiter(JUnit 5)作为核心测试引擎,而你的自定义@MyTest注解是基于JUnit 4的规则设计的,两者的测试注解识别机制完全不同:

  • JUnit 4依赖运行器(如SpringJUnit4ClassRunner)扫描测试方法,会识别被JUnit 4的@Test元注解标注的自定义注解;
  • JUnit 5则通过扩展机制处理,默认仅识别自身的@Test注解及被其元注解标注的自定义注解,且要求测试类适配JUnit 5的扩展体系。

替换依赖后,测试环境默认切换到JUnit 5,你的自定义注解不符合其识别规则,因此出现无法识别的问题;即使你给@MyTest添加了@Test,如果是JUnit 4的@Test,JUnit 5引擎也不会识别,导致执行时提示"No tests were found",而IntelliJ只是通过语法扫描识别到@Test标记,所以显示可运行但实际无法执行。

解决方案

方案1:继续使用JUnit 4

如果要保留JUnit 4的测试体系,按以下步骤调整:

  1. 修改@MyTest注解,确保标注的是JUnit 4的@Test:
import org.junit.Test;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE })
@Retention(RUNTIME)
@Test // 此处为JUnit 4的org.junit.Test
public @interface MyTest{}
  1. 在测试类上添加JUnit 4的运行器注解:
import org.junit.runner.RunWith;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
public class YourTestClass {
    @MyTest
    public void yourTestMethod() {
        // 测试逻辑
    }
}
  1. 确保依赖中包含JUnit 4兼容引擎(spring-boot-starter-test 2.7.x默认已包含,若缺失可显式引入):
<dependency>
    <groupId>org.junit.vintage</groupId>
    <artifactId>junit-vintage-engine</artifactId>
    <scope>test</scope>
</dependency>

方案2:迁移到JUnit 5(推荐)

Spring Boot 2.7.x虽兼容JUnit 4,但后续版本会逐步移除对JUnit 4的支持,建议迁移到JUnit 5:

  1. 修改@MyTest注解,使用JUnit 5的@Test和Spring扩展注解:
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE })
@Retention(RUNTIME)
@Test // 此处为JUnit 5的org.junit.jupiter.api.Test
@ExtendWith(SpringExtension.class)
public @interface MyTest{}
  1. 测试类使用JUnit 5的Spring测试注解(如@SpringBootTest,默认已集成SpringExtension):
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
public class YourTestClass {
    @MyTest
    public void yourTestMethod() {
        // 测试逻辑
    }
}
  1. 确保IntelliJ的运行配置选择JUnit 5作为测试运行器(默认会根据注解自动识别)。

内容的提问来源于stack exchange,提问作者David S

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 04:13:09