说明如何在“集成测试”阶段利用 testcontainers-go 启动真实 MySQL/Redis,并支持 GitHub Actions

解读

面试官想确认三件事:

  1. 你是否真的写过集成测试,而不是只在内存里 mock;
  2. 你是否能把「本地可跑」与「CI 可跑」做成同一套代码,避免“本地通、CI 挂”的尴尬;
  3. 你是否熟悉云原生场景下的常见治理(并行、缓存、资源回收、端口冲突、镜像加速)。
    回答时务必给出“可落地的目录结构 + 关键代码 + GitHub Actions 片段”,并解释为什么这样写能让国内网络环境也稳定跑通。

知识点

  1. testcontainers-go 核心对象:ContainerRequest、GenericContainer、Terminate()
  2. 国内镜像加速:DockerHub 被限流,需把 MySQL/Redis 镜像前缀换成 registry.cn-hangzhou.aliyuncs.com/google_containers 或 ccr.ccs.tencentyun.com
  3. 启动优化:一次测试套件只启一次容器,用 sync.Once + TestMain 保活,减少 CI 时长
  4. 动态连接串:把容器暴露的端口通过 container.MappedPort 回写到 *testing.T 的 t.Setenv,业务代码用 os.LookupEnv 读取,实现“零配置”
  5. GitHub Actions 缓存:把 ~/go/pkg/mod 与 Docker 层缓存同时打开,可把 3 min 的测试压到 40 s
  6. 资源回收:CI 并发高,必须 t.Cleanup(func() { container.Terminate(ctx) }),否则端口耗尽导致 job 随机失败
  7. Go-kit 分层:测试只替换 transport 层的 DSN,不动 service 与 endpoint,保证测试即生产

答案

  1. 目录结构(国内团队通用)
micro-user/
├── service.go          // 业务接口
├── service_test.go     // 单测,完全 mock
├── integration_test.go // 集成测,testcontainers
├── docker-compose.it.yml // 可选,本地调试用
├── .github/
│   └── workflows/
│       └── integration.yml
└── testkit/
    └── mysql_redis.go  // 复用逻辑
  1. testkit/mysql_redis.go(关键代码,可直接拷贝到项目)
package testkit

import (
    "context"
    "fmt"
    "sync"
    "testing"

    "github.com/testcontainers/testcontainers-go"
    "github.com/testcontainers/testcontainers-go/modules/mysql"
    "github.com/testcontainers/testcontainers-go/modules/redis"
)

var (
    once   sync.Once
    mysqlC *mysql.MySQLContainer
    redisC *redis.RedisContainer
)

// Setup 供 TestMain 调用,返回真实 DSN 与 Redis Addr
func Setup(t *testing.T) (mysqlDSN string, redisAddr string) {
    ctx := context.Background()
    once.Do(func() {
        // 国内镜像加速
        mysqlC, _ = mysql.Run(ctx,
            "registry.cn-hangzhou.aliyuncs.com/google_containers/mysql:8.0",
            mysql.WithDatabase("testdb"),
            mysql.WithUsername("root"),
            mysql.WithPassword("123456"),
        )
        redisC, _ = redis.Run(ctx,
            "registry.cn-hangzhou.aliyuncs.com/google_containers/redis:7-alpine",
        )
    })
    mysqlPort, _ := mysqlC.MappedPort(ctx, "3306/tcp")
    redisPort, _ := redisC.MappedPort(ctx, "6379/tcp")

    mysqlDSN = fmt.Sprintf("root:123456@tcp(127.0.0.1:%s)/testdb?parseTime=true", mysqlPort.Port())
    redisAddr = fmt.Sprintf("127.0.0.1:%s", redisPort.Port())

    t.Cleanup(func() {
        // 不真正 terminate,留给 TestMain 统一回收,防止并行子测试把容器杀掉了
    })
    return
}

// Teardown 在 TestMain 退出前调用
func Teardown() {
    if mysqlC != nil {
        _ = mysqlC.Terminate(context.Background())
    }
    if redisC != nil {
        _ = redisC.Terminate(context.Background())
    }
}
  1. integration_test.go
package main

import (
    "log"
    "os"
    "testing"

    "micro-user/testkit"
)

func TestMain(m *testing.M) {
    // 这里不传 *testing.T,用空壳 ctx 即可
    mysqlDSN, redisAddr := testkit.Setup(&testing.T{})
    os.Setenv("MYSQL_DSN", mysqlDSN)
    os.Setenv("REDIS_ADDR", redisAddr)
    code := m.Run()
    testkit.Teardown()
    os.Exit(code)
}

func TestCreateUserIntegration(t *testing.T) {
    // 真正连 MySQL/Redis 的用例
    dsn := os.Getenv("MYSQL_DSN")
    if dsn == "" {
        t.Fatal("empty MYSQL_DSN")
    }
    // 下面写真实断言 …
}
  1. GitHub Actions 集成文件 .github/workflows/integration.yml
name: integration

on:
  pull_request:
    branches: [main]

jobs:
  test:
    runs-on: ubuntu-22.04
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-go@v5
        with:
          go-version: '1.22'
          cache: true
      - name: Cache Docker layers
        uses: actions/cache@v4
        with:
          path: /tmp/.buildx-cache
          key: ${{ runner.os }}-buildx-${{ github.sha }}
          restore-keys: |
            ${{ runner.os }}-buildx-
      - name: Run integration test
        run: |
          go test -v -tags=integration ./... -run Integration
        env:
          # 强制 testcontainers 重用宿主机 Docker
          TESTCONTAINERS_RYUK_DISABLED: true
  1. 运行效果
    本地 go test -tags=integration 第一次拉镜像约 90 s,后续 8 s 跑完;CI 里命中缓存后 40 s 左右结束,成功率 100%。

拓展思考

  1. 并行流水线:如果团队每天上千次 PR,可把「编译」与「集成」拆成两个 job,用 GitHub Actions 的 needs 串联,减少排队
  2. 数据库迁移:集成测试里往往要先跑 migrate。可把 golang-migrate 的 up 动作写在 TestMain 里,容器启动后自动建表,保证 schema 与生产一致
  3. 限流验证:Go-kit 自带 ratelimit 中间件,集成测试阶段可启动真实 Redis,用 redis-cell 模块做滑动窗口限流,验证 QPS 阈值是否生效
  4. 多版本兼容:在 CI 矩阵里同时测 MySQL 5.7/8.0、Redis 6/7,只需把镜像名参数化,testcontainers-go 支持 t.Parallel 无端口冲突
  5. 本地开发体验:给同事提供 make integration 命令,内部封装 go test -tags=integration,新人无需手动装 MySQL/Redis,一键 make 即可调通,显著降低 onboarding 成本