springboot中的怎么用JUnit进行测试的?

在 Spring Boot 中使用 JUnit 进行单元测试非常简单,官方已帮你集成好 JUnit5(Spring Boot 2.x 默认),只需 3 步即可跑起来。下面给出一份「最小可运行」示例,并补充常见场景(Mock、Web、事务)的写法,复制即可用。

1.引入依赖(已自带,确认即可)

XML 复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

该包已包含 JUnit5、Mockito、AssertJ、Hamcrest 等,无需额外导包

2.最简单的 service 层单元测试

java 复制代码
@SpringBootTest                      // 1. 拉起整个 Spring 容器
class UserServiceTest {

    @Autowired
    private UserService userService;   // 2. 直接注入真实 Bean

    @Test                              // 3. JUnit5 注解
    void getUserById() {
        User u = userService.getById(1L);
        assertThat(u.getName()).isEqualTo("Jack");   // AssertJ 流式断言
    }
}

运行:IDEA 在方法左侧点击 ▶ 即可,首次会自动编译并启动容器,完成后看到绿色条即通过

3.常见场景快速模板

|--------------------|----------------------------------------------------------------------|
| 场景 | 关键注解/工具 |
| ① 不启动服务器,只测 web 切片 | @WebMvcTest(YourController.class) + MockMvc |
| ② 快速 Mock 依赖 | @MockBean |
| ③ 测试持久层 | @DataJpaTest + @AutoConfigureTestDatabase(replace=ANY) |
| ④ 事务回滚 | @Transactional(默认回滚) |
| ⑤ 随机端口 HTTP 测试 | @SpringBootTest(webEnvironment = RANDOM_PORT) + TestRestTemplate |

4.JUnit4 → JUnit5 对照(老项目迁移)

| JUnit4 | JUnit5 |

|---|---|

| @RunWith(SpringRunner.class) | 不需要,或改为 @ExtendWith(SpringExtension.class) |

| @Test(org.junit.Test) | @Test(org.junit.jupiter.api.Test) |

| Assert.assertEquals | Assertions.assertEqualsassertThat(...).isEqualTo(...) |

5.一键生成测试类小技巧

在 IDEA 里把光标停在要测试的类名上 → Ctrl+Shift+T → Create New Test → 选择 JUnit5,IDE 会自动在 src/test/java 对应包下生成模板,再补 @SpringBootTest 即可

6.运行与查看报告

  • 命令行:mvn test

  • 报告:target/surefire-reports/index.html(Maven)

  • 覆盖率:加 jacoco-maven-plugin 后执行 mvn test jacoco:report,打开 target/site/jacoco/index.html 即可看到行/分支覆盖率

照着以上模板,10 分钟即可把 Spring Boot 项目的单元测试跑起来;后续再按需拆分层级测试(@WebMvcTest、@DataJpaTest 等)即可。祝编码愉快!

相关推荐
学传打活4 小时前
古代汉语是源,现代汉语是流,源与流一脉相承。
微信公众平台·1024程序员节·汉字·中华文化
jaysee-sjc1 天前
十七、Java 高级技术入门全解:JUnit、反射、注解、动态代理
java·开发语言·算法·junit·intellij-idea
橘子编程3 天前
软件测试全流程实战指南
java·功能测试·测试工具·junit·tomcat·压力测试·可用性测试
学传打活5 天前
【边打字.边学昆仑正义文化】_19_星际生命的生存状况(1)
微信公众平台·1024程序员节·汉字·昆仑正义文化
DJ斯特拉7 天前
Redis使用lua脚本
junit·单元测试·lua
2301_771717217 天前
idea中springboot中使用junit测试报错的解决方案
spring boot·junit·intellij-idea
Java成神之路-8 天前
Spring 整合 MyBatis 全流程详解(附 Junit 单元测试实战)(Spring系列6)
spring·junit·mybatis
難釋懷9 天前
OpenResty封装Redis工具
redis·junit·openresty
希望永不加班11 天前
SpringBoot 接口测试:Postman 与 JUnit 5 实战
java·spring boot·后端·junit·postman
難釋懷11 天前
OpenResty基于ID负载均衡
junit·负载均衡·openresty