springboot+mybatis单元测试
时间: 2025-07-10 19:03:46 浏览: 4
在 Spring Boot 与 MyBatis 集成的项目中进行单元测试,通常需要结合 `JUnit` 测试框架和 Spring 提供的测试支持模块。以下是编写和运行单元测试的具体方法:
### 单元测试依赖配置
首先,在项目的 `pom.xml` 文件中确保包含以下测试相关依赖:
```xml
<dependencies>
<!-- JUnit 测试框架 -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.8.1</version>
<scope>test</scope>
</dependency>
<!-- Spring Boot 测试支持 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
```
### 编写单元测试类
Spring Boot 提供了专门的注解来支持测试,例如 `@SpringBootTest` 和 `@DataJpaTest`(对于 MyBatis,则不需要这个)。为了加载完整的上下文以支持 MyBatis 组件,可以使用 `@SpringBootTest` 注解,并结合 `@MapperScan` 或者直接注入 Mapper 接口。
以下是一个简单的单元测试示例:
```java
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest
public class UserMapperTest {
@Autowired
private UserMapper userMapper;
@Test
public void testSelectUserById() {
// 假设数据库中存在 id 为 1 的用户
User user = userMapper.selectUserById(1L);
assertNotNull(user); // 确保查询结果不为空
assertEquals("John Doe", user.getName()); // 根据实际情况调整期望值
}
}
```
上述代码中:
- `@SpringBootTest` 会启动整个 Spring 上下文,适合集成测试。
- `@Autowired` 自动注入对应的 Mapper 实例。
- 在测试方法中调用实际业务逻辑并验证结果。
### 数据库连接配置
在 `application.yml` 中,测试环境下可以启用内存数据库或者使用本地开发数据库[^2]:
```yaml
spring:
datasource:
url: jdbc:mysql://localhost:3306/test_db
username: root
password: yourpassword
driver-class-name: com.mysql.cj.jdbc.Driver
```
如果希望使用内存数据库(如 H2)来隔离测试数据,可以替换为:
```yaml
spring:
datasource:
url: jdbc:h2:mem:testdb
driver-class-name: org.h2.Driver
username: sa
password:
```
### 使用事务控制
为了避免测试对真实数据库造成影响,可以在测试方法上添加 `@Transactional` 注解,这样每个测试方法执行后都会自动回滚事务:
```java
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.transaction.annotation.Transactional;
@SpringBootTest
@Transactional
public class UserServiceTest {
@Autowired
private UserService userService;
@Test
public void testCreateUser() {
User newUser = new User("Jane Smith");
userService.createUser(newUser);
assertNotNull(newUser.getId()); // 确保保存后生成 ID
}
}
```
### 日志和调试
可以通过日志输出查看 SQL 执行情况,这有助于排查问题。在 `application.yml` 中启用日志级别:
```yaml
logging:
level:
com.example.mapper: debug # 替换为实际的包路径
```
###
阅读全文
相关推荐


















