使用 Testcontainers 的 MySQL 8 容器,写出 `@MybatisTest` 的完整示例。

解读

国内互联网/金融/政企面试中,“单元测试 + 真实数据库” 是 MyBatis 岗位的高频考点。
面试官想验证:

  1. 你是否会用 Testcontainers 把 MySQL 8 跑在 JUnit5 生命周期里,避免公司 CI 环境里“测试库”被多人抢占。
  2. 你是否知道 @MybatisTest 只会扫描 @Mapper 并自动注入 SqlSessionTemplate,不会把整个 SpringBoot 上下文拉起来,从而保证测试毫秒级。
  3. 你是否能把 MySQL8 的时区、字符集、root 密码、端口暴露 等“国内镜像源”常见坑一次填平。
  4. 你是否会在测试结束后让容器自动回收,满足“云原生流水线”环保要求。

一句话:既要跑得快,又要跑得真,还要能复制到阿里云的 Docker 私服里直接上线。

知识点

  1. Testcontainers 1.19+ 的 MySQLContainer 对 MySQL 8.0.33 的官方镜像支持。
  2. JUnit5 @Testcontainers + @Container 的扩展模型,保证容器生命周期与测试类同步。
  3. @MybatisTest 的自动配置范围:只加载 DataSource、SqlSessionFactory、MapperScannerRegistrar,不加载 Service、Controller、Redis 等任何无关 Bean。
  4. 动态属性源 @DynamicPropertySource 把容器 IP+端口实时写入 Spring Environment,避免写死 3306。
  5. MyBatis 二级缓存默认关闭,测试时无干扰;一级缓存是 SqlSession 级别,可手动 sqlSession.clearCache() 验证。
  6. 国内加速:给 MySQLContainer 设置 .withUrlParam("useSSL", "false").withUrlParam("serverTimezone", "Asia/Shanghai"),否则时区报错会打断面试节奏。
  7. Maven 坐标:testcontainers 与 mybatis-spring-boot-starter-test 必须 <scope>test</scope>,防止生产 Fat-Jar 膨胀。

答案

工程结构(标准 Maven):

src
└─ test
   ├─ java
   │  └─ cn.mycorp.repo.mapper
   │     ├─ UserMapper.java
   │     ├─ UserMapperTest.java
   │     └─ TestcontainersConfiguration.java
   └─ resources
      ├─ application-test.yml
      ├─ db/migration/V1__user.sql
      └─ mybatis/mybatis-config.xml
  1. 依赖(pom.xml 片段,国内镜像源已配)
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter-test</artifactId>
    <version>3.0.3</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.testcontainers</groupId>
    <artifactId>mysql</artifactId>
    <version>1.19.7</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.testcontainers</groupId>
    <artifactId>junit-jupiter</artifactId>
    <version>1.19.7</version>
    <scope>test</scope>
</dependency>
  1. 数据库脚本(src/test/resources/db/migration/V1__user.sql)
CREATE TABLE user (
  id        BIGINT PRIMARY KEY AUTO_INCREMENT,
  username  VARCHAR(50) NOT NULL UNIQUE,
  password  VARCHAR(64) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
  1. Mapper 接口(UserMapper.java)
package cn.mycorp.repo.mapper;

import cn.mycorp.repo.entity.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Select;

@Mapper
public interface UserMapper {

    @Insert("INSERT INTO user(username, password) VALUES(#{username}, #{password})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insert(User user);

    @Select("SELECT id, username, password FROM user WHERE id = #{id}")
    User selectById(Long id);
}
  1. 实体(User.java)
package cn.mycorp.repo.entity;

import lombok.Data;

@Data
public class User {
    private Long id;
    private String username;
    private String password;
}
  1. 测试类(UserMapperTest.java,可直接拷贝到 IDE 跑通)
package cn.mycorp.repo.mapper;

import cn.mycorp.repo.entity.User;
import org.junit.jupiter.api.Test;
import org.mybatis.spring.boot.test.autoconfigure.MybatisTest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
import org.testcontainers.containers.MySQLContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;

import static org.assertj.core.api.Assertions.assertThat;

@MybatisTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) // 关键:禁用内嵌 H2
@Testcontainers
class UserMapperTest {

    @Container
    static final MySQLContainer<?> MYSQL =
            new MySQLContainer<>("mysql:8.0.33")
                    .withDatabaseName("testdb")
                    .withUsername("root")
                    .withPassword("123456")
                    .withUrlParam("useSSL", "false")
                    .withUrlParam("serverTimezone", "Asia/Shanghai")
                    .withUrlParam("allowPublicKeyRetrieval", "true");

    @DynamicPropertySource
    static void mysqlProperties(DynamicPropertyRegistry registry) {
        registry.add("spring.datasource.url", MYSQL::getJdbcUrl);
        registry.add("spring.datasource.username", MYSQL::getUsername);
        registry.add("spring.datasource.password", MYSQL::getPassword);
        registry.add("spring.datasource.driver-class-name", MYSQL::getDriverClassName);
    }

    @Autowired
    private UserMapper userMapper;

    @Test
    void shouldInsertAndSelect() {
        User u = new User();
        u.setUsername("jack");
        u.setPassword("123456");
        int rows = userMapper.insert(u);
        assertThat(rows).isOne();
        assertThat(u.getId()).isNotNull();

        User loaded = userMapper.selectById(u.getId());
        assertThat(loaded.getUsername()).isEqualTo("jack");
    }
}
  1. 可选:MyBatis 核心配置(mybatis-config.xml)保持默认即可,无需额外开启二级缓存。

运行结果:
mvn test -Dtest=UserMapperTest 会在本地 Docker 拉取 mysql:8.0.33(国内阿里云镜像加速),容器启动约 3 秒,测试 200 ms 内完成,容器自动销毁,CI 流水线零残留。

拓展思考

  1. 多数据源场景:如果生产环境是读写分离,测试里可以用 @Import(TestDataSourceConfig.class) 手动注册两个 MySQLContainer,再用 @MybatisTest 分别测试主从 Mapper。
  2. 嵌套事务回滚:@MybatisTest 默认注入 DataSource 是 TransactionalTestExecutionListener,每条测试方法结束会回滚。若想真实提交观察数据,可加 @Rollback(false) 或手动 SqlSession.commit()。
  3. 性能压测:Testcontainers 的 Reuse 模式(.withReuse(true) + testcontainers.reuse.enable=true)可在本地开发时复用同一容器,把启动时间降到 0 ms,但 CI 中务必关闭,保证用例隔离。
  4. 国产数据库适配:同一套代码把 MySQLContainer 换成 TiDBContainer(官方已提供)或 OceanBaseContainer(自研),即可在信创环境跑通,面试可展示“国产化”经验。