阿飞
阿飞
发布于 2025-06-13 / 6 阅读
0
0

springboot3之将junit4迁移到junit5

迁移原因: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进行更新替换

查找内容

替换内容

import org.junit.Test;

import org.junit.jupiter.api.Test;

import org.junit.runner.RunWith;

import org.junit.jupiter.api.extension.ExtendWith;

import org.springframework.test.context.junit.jupiter.SpringExtension;

@RunWith(SpringRunner.class)

@ExtendWith(SpringExtension.class)

---移除--->

import org.springframework.test.context.junit4.SpringRunner;

import org.junit.Before;

import org.junit.jupiter.api.BeforeEach;

@Before

@BeforeEach
(⚠️注意不要替换import org.aspectj.lang.annotation.Before;的注解)

Assert

Assertions

import org.junit.Assert;

import org.junit.jupiter.api.Assertions;

注解与导入更新

JUnit 4 注解

JUnit 5 注解

说明

@Test

@Test

包路径变更:org.junit.jupiter.api

@Before

@BeforeEach

@After

@AfterEach

@BeforeClass

@BeforeAll

需配合 static 方法

@RunWith(SpringRunner.class)

@ExtendWith(SpringExtension.class)

Spring 测试集成

断言与假设重写

  • 断言迁移示例

  // 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。


评论