迁移原因:Spring Boot 3 默认集成 JUnit 5,不再支持 JUnit 4 的 SpringRunner。
🔧 一、依赖调整
移除 JUnit 4
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
添加 JUnit 5
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.13.1</version>
<scope>test</scope>
</dependency>
JUnit5同时兼容JUnit4
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<scope>test</scope>
</dependency>
总结的快速替换更新
可以使用IDEA的Ctrl+R
进行更新替换
注解与导入更新
断言与假设重写
断言迁移示例:
// JUnit 4
assertEquals("message", expected, actual);
// JUnit 5
assertEquals(expected, actual, "message"); // 消息参数移至末尾
超时与异常测试:
// 异常检查
assertThrows(Exception.class, () -> methodCall());
// 超时检查
assertTimeout(Duration.ofSeconds(1), () -> operation());
规则(Rules)迁移
JUnit 4 的 @Rule 和 @ClassRule 被 @ExtendWith 替代:
@ExtendWith(MockitoExtension.class) // 替代 MockitoJUnitRunner
public class MyTest { ... }
5. 参数化测试改造
@ParameterizedTest
@ValueSource(ints = {2, 4, 8})
void testEven(int num) {
assertEquals(0, num % 2);
}
需额外依赖 junit-jupiter-params。
自动化迁移工具
OpenRewrite:
通过 Maven 插件自动重构代码:
<plugin>
<groupId>org.openrewrite.maven</groupId>
<artifactId>rewrite-maven-plugin</artifactId>
<configuration>
<activeRecipes>
<recipe>org.openrewrite.java.spring.boot2.SpringBoot2JUnit4to5Migration</recipe>
</activeRecipes>
</configuration>
</plugin>
运行:mvn rewrite:run。