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的测试体系,按以下步骤调整:
- 修改
@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{}
- 在测试类上添加JUnit 4的运行器注解:
import org.junit.runner.RunWith; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) public class YourTestClass { @MyTest public void yourTestMethod() { // 测试逻辑 } }
- 确保依赖中包含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:
- 修改
@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{}
- 测试类使用JUnit 5的Spring测试注解(如
@SpringBootTest,默认已集成SpringExtension):
import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest public class YourTestClass { @MyTest public void yourTestMethod() { // 测试逻辑 } }
- 确保IntelliJ的运行配置选择JUnit 5作为测试运行器(默认会根据注解自动识别)。
内容的提问来源于stack exchange,提问作者David S
相关产品推荐
相关产品推荐

