六、SpringBoot整合Junit

5.2.1 添加Junit的起步依赖

XML 复制代码
<!--测试的起步依赖-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

5.2.2 编写测试类

java 复制代码
package com.baijie.fast_springboot_project;

import com.baijie.FastSpringbootProjectApplication;
import com.baijie.domain.User;
import com.baijie.mapper.UserMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;
@SpringBootTest
class FastSpringbootProjectApplicationTests {

	@Autowired
	private UserMapper userMapper;

	@Test
	void contextLoads() {
		System.out.println(666);
		List<User> users = userMapper.queryUserList();
		for (User user : users) {
			System.out.println(user.toString());
		}
	}
}

【备注】

**在SpringBoot2.2.0以前是JUnit4,需@RunWith注解。**下图:

**在SpringBoot之后是JUnit5。SpringBoot的高级版本使用junit5进行单元测试,无需@RunWith注解即可进行测试。**如图:

【备注】

@SpringBootTest替代了spring-test中的@ContextConfiguration注解,目的是加载ApplicationContext,启动spring容器。

使用@SpringBootTest时并没有像@ContextConfiguration一样显示指定locations或classes属性,原因在于@SpringBootTest注解会自动检索程序的配置文件,检索顺序是从当前包开始,逐级向上查找被@SpringBootApplication或@SpringBootConfiguration注解的类。

5.2.3 控制台打印信息

相关推荐
想用offer打牌5 小时前
MCP (Model Context Protocol) 技术理解 - 第二篇
后端·aigc·mcp
KYGALYX7 小时前
服务异步通信
开发语言·后端·微服务·ruby
掘了7 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
爬山算法7 小时前
Hibernate(90)如何在故障注入测试中使用Hibernate?
java·后端·hibernate
猫头虎7 小时前
如何排查并解决项目启动时报错Error encountered while processing: java.io.IOException: closed 的问题
java·开发语言·jvm·spring boot·python·开源·maven
Moment8 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
Cobyte8 小时前
AI全栈实战:使用 Python+LangChain+Vue3 构建一个 LLM 聊天应用
前端·后端·aigc
程序员侠客行9 小时前
Mybatis连接池实现及池化模式
java·后端·架构·mybatis
Honmaple9 小时前
QMD (Quarto Markdown) 搭建与使用指南
后端