如何结合 build tag 与 testify 实现“仅本地”集成测试

解读

国内云原生岗位面试中,**“本地可跑、线上不跑”**的集成测试是高频考点。
核心矛盾有三点:

  1. 集成测试依赖本地 Docker、MySQL、Kafka 等重型服务,CI 环境不一定具备;
  2. 测试文件不能混入单元测试,否则 go test ./... 会全部触发,拖慢流水线;
  3. 需要一套断言库让用例写得快、报错可读,testify 是国内团队事实标准。

因此,面试官想确认候选人能否用 build tag 做编译期隔离,再叠加 testify 完成高可读断言,并给出可落地的工程规范。

知识点

  1. build tag 语法规则

    • 文件头 //go:build localintegration(Go 1.18+)或旧写法 // +build localintegration
    • 标签是“与”关系,空格分隔;取反用 !,例如 //go:build localintegration && linux
    • 标签只在当前包生效,跨包需每个测试文件都写
  2. testify 核心组件

    • github.com/stretchr/testify/suite:结构化 Setup/TearDown,国内项目普遍采用
    • assert/require:断言失败语义,前者继续执行,后者立即返回
  3. go test 标签过滤

    • 运行带标签:go test -tags=localintegration ./...
    • 排除标签:go test -tags="!localintegration" ./...,CI 默认用此命令
  4. Makefile 与 IDE 友好

    • 本地集成测试统一 make test-integration;CI 跑 make test-unit
    • Goland/VSCode 需要在设置里把 -tags=localintegration 写到 go.testFlags,否则 IDE 不识别
  5. 依赖启动与优雅终止

    • 使用 ory/dockertest 或 testcontainers-go 在 TestMain 里拉起容器,suite.SetupSuite 只放连接确认逻辑,避免重复拉镜像
    • 通过 sync.Once 保证多测试文件只启动一次基础设施,加快本地反馈

答案

步骤一:创建测试文件 internal/order/repo_integration_test.go,头部声明标签

//go:build localintegration
package repo_test

步骤二:引入 testify suite 骨架

import (
    "context"
    "testing"
    "github.com/stretchr/testify/suite"
    "myapp/internal/order"
)

type OrderRepoSuite struct {
    suite.Suite
    repo *order.Repo
    pool *dockertest.Pool
    res  *dockertest.Resource
}

func (s *OrderRepoSuite) SetupSuite() {
    var err error
    s.pool, err = dockertest.NewPool("")
    s.Require().NoError(err)
    s.res, err = s.pool.Run("mysql", "8.0", []string{"MYSQL_ROOT_PASSWORD=root"})
    s.Require().NoError(err)
    dsn := fmt.Sprintf("root:root@tcp(localhost:%s)/test", s.res.GetPort("3306/tcp"))
    s.repo, err = order.NewRepo(dsn)
    s.Require().NoError(err)
}

func (s *OrderRepoSuite) TearDownSuite() {
    s.NoError(s.pool.Purge(s.res))
}

func TestOrderRepo(t *testing.T) {
    suite.Run(t, new(OrderRepoSuite))
}

func (s *OrderRepoSuite) TestCreateAndGet() {
    ctx := context.Background()
    id, err := s.repo.Create(ctx, &order.Entity{Amount: 100})
    s.NoError(err)
    s.NotZero(id)

    got, err := s.repo.Get(ctx, id)
    s.NoError(err)
    s.Equal(int64(100), got.Amount)
}

步骤三:本地运行

go test -tags=localintegration -v ./internal/order/...

CI 流水线默认执行

go test -tags="!localintegration" -race -coverprofile=coverage.out ./...

即可实现“本地能跑、线上不跑”的硬隔离。

拓展思考

  1. 多标签组合场景
    若团队同时存在 redis 集成、mysql 集成,可定义 //go:build integration && redis 与 //go:build integration && mysql,Makefile 提供组合命令 make test-redis,实现更细粒度筛选。

  2. 缓存基础设施
    本地每次 go test 都重拉镜像依然慢,可把 dockertest 的 Pool.MaxWait 调短,并引入 github.com/ory/dockertest/v3 的 Expire 选项,让容器在后台复用 30 分钟,显著缩短反馈时间。

  3. 与 BDD 结合
    在 testify suite 之上再包一层 github.com/stretchr/testify/mock,把外部依赖 mock 掉后可降级为单元测试;同一套用例通过标签切换“真实依赖”与“mock 依赖”,实现“一份代码,两种运行模式”,这是国内中大型微服务项目的常见套路。