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

如何在无@RunWith注解及JUnit 4依赖下运行JUnit 5测试套件?

不依赖JUnit 4实现JUnit 5测试套件的方案

当然可以!完全不需要依赖JUnit 4就能搭建JUnit 5的测试套件——而且根本不用@ExtendsWith,JUnit 5本身就提供了原生的套件支持,比原来依赖JUnit 4的方式更简洁、更符合JUnit 5的设计思路。

替代方案:使用JUnit 5原生套件注解

原来的@RunWith(JUnitPlatform.class)是为了让JUnit 4的运行器兼容执行JUnit 5测试,现在JUnit 5已经有了自己的套件定义方式,直接用下面这套注解就能替代:

import org.junit.platform.suite.api.ExcludeTags;
import org.junit.platform.suite.api.SelectPackages;
import org.junit.platform.suite.api.Suite;

@Suite
@SelectPackages("com.services.configuration")
@ExcludeTags({IntegrationTags.JPA, IntegrationTags.REST})
public class UnitTestSuite { }

注解说明

  • @Suite:这是JUnit 5测试套件的核心标记,告诉测试运行器这个类是一个套件入口
  • @SelectPackages:和你原来的注解作用完全一致,指定要扫描的测试包路径
  • @ExcludeTags:功能和原来的一样,排除带有指定标签的测试类或方法

依赖调整

你需要把原来的junit-platform-runner依赖替换成JUnit 5的套件引擎依赖,同时移除所有JUnit 4相关的依赖:

  • Maven依赖:
<dependency>
    <groupId>org.junit.platform</groupId>
    <artifactId>junit-platform-suite-engine</artifactId>
    <version>1.10.0</version> <!-- 建议使用和你JUnit 5版本匹配的版本 -->
    <scope>test</scope>
</dependency>
  • Gradle依赖:
testImplementation 'org.junit.platform:junit-platform-suite-engine:1.10.0'

这样配置完成后,你的测试套件就能完全脱离JUnit 4依赖,直接用JUnit 5的运行器执行了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:20:47