Spring Boot 3.2 BOM 已包含 `junit-bom`,为何仍需手动声明 `junit-jupiter` 版本?

解读

国内大多数企业把 Spring Boot 的 spring-boot-dependencies 作为“唯一可信源”,认为只要继承了该 BOM,所有测试相关坐标就应该自动收敛。
然而 Maven 的依赖仲裁只看“直接声明优先”与“最短路径优先”,并不因为某个 BOM 里存在 junit-jupiter 就强行把它注入你的模块。
Spring Boot 3.2 的 BOM 里确实通过 junit-bom 统一了 5.10.x 的版本号,但没有提供任何 junit-jupiter 的 dependency 条目;换句话说,它只“锁版本”,不“引依赖”。
如果你的 pom.xml 里没有直接或间接地声明 junit-jupiter,Maven 在编译 test-sources 阶段就根本见不到 org.junit.jupiter.api.Test 等类,导致 maven-surefire-plugin 报 No tests were executed 或者 ClassNotFoundException。
因此,“BOM 包含”≠“依赖自动进来”,仍需手动声明一次坐标,版本则由 Spring Boot BOM 接管,无需再写数字。

知识点

  1. Maven 依赖传递三原则:直接声明优先、最短路径优先、先声明优先;BOM 只干预 version,不参与传递。
  2. scope=test 的依赖默认不会向下传递,所以父 POM 里即使声明了 junit-jupiter,子模块也看不见。
  3. spring-boot-dependencies 采用 import 方式叠放多个第三方 BOM(如 junit-bom、mockito-bom、assertj-bom),仅做版本对齐,不替代用户显式依赖。
  4. Surefire 插件 3.x 默认的 providers 列表里不再预装 junit-platform-engine,必须保证 junit-jupiter-engine 出现在 test classpath,否则无法识别 @Test。
  5. 国内企业私有 Nexus 仓库常把 * 的 test 构件设为“不缓存”,若本地仓库被清理,缺少显式声明会导致 CI 节点拉不到包,构建随机失败。

答案

Spring Boot 3.2 BOM 仅通过 junit-bom 锁定了 Jupiter 各模块的版本号,但并未替你引入任何实际依赖。
Maven 只有在检测到至少一条对 junit-jupiter 的直接或传递依赖时,才能把对应 JAR 拉进 test classpath。
因此,为了让 maven-surefire-plugin 找到 junit-jupiter-engine 并执行 @Test,必须在模块的 dependencies 里显式声明:

<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter</artifactId>
    <scope>test</scope>
</dependency>

版本号由 Spring Boot BOM 统一管控,无需手写;若再次硬编码版本,反而会覆盖 BOM 的仲裁,造成版本漂移与二进制不兼容风险。

拓展思考

  1. 在多模块项目中,把 junit-jupiter 声明到父 POM 的 <dependencyManagement> 并配上 scope=test,仍不会让子模块自动获得;正确做法是使用 <dependencies> 区块,或者新建一个 test-support 模块,通过 test-jar 方式间接引入。
  2. 如果团队想强制所有子模块统一使用 Jupiter,可自定义企业级 BOM,在 BOM 里直接声明 junit-jupiter 的 dependency 而非 dependencyManagement,再让业务应用继承;这种做法打破了“BOM 不引包” 的惯例,需要充分评审传递范围。
  3. Gradle 用户切换到 Maven 时,常误以为 implementation platform('org.springframework.boot:spring-boot-dependencies:3.2.x') 等价于 Maven 的 import BOM,结果漏写 testImplementation 'org.junit.jupiter:junit-jupiter',出现同样问题;说明工具链差异不在于 BOM,而在于**“显式依赖”思维**。
  4. 在云原生 CI 场景下,为了加速镜像构建,可把 junit-jupiter 与 surefire-provider 预先打包到构建缓存层;此时仍需保留空版本坐标,否则缓存层与业务层会出现双版本冲突,导致native-test 阶段失败。