Gin 如何用 httptest 创建 context 并注入 mock service?

解读

在国内一线/二线互联网公司的 Go 后端面试里,这道题出现的频率极高。它考察的不是“会不会写单测”,而是“能不能在不启动真实端口、不依赖第三方组件的前提下,把依赖(MySQL、Redis、RPC 客户端)全部 mock 掉,并保证测试用例可并发、可重复、可跑在 CI 上”。
很多候选人只答出“用 httptest.NewRecorder”就停住,结果一面直接挂。面试官想听到的是:

  1. 如何构造一个完全隔离的 *gin.Context;
  2. 如何把 mock service 注入到 context 里,并保证 handler 能拿到;
  3. 如何断言中间件、handler、渲染结果、状态码、header、body 一个不落;
  4. 如何做到并发安全、用例之间零污染。

知识点

  1. httptest 包:NewRequest 创建 *http.Request,NewRecorder 返回 *httptest.ResponseRecorder,两者组合可模拟一次 HTTP 调用。
  2. gin.CreateTestContext:官方提供的测试辅助函数,返回 *gin.Context 与自定义的 *httptest.ResponseRecorder,避免走端口监听。
  3. context.WithValue 与 gin.Context.Set:Gin 的上下文底层复用了 go 原生的 context.Context,但对外暴露的是 gin.Context.Set/Get,测试时优先用 gin 自己的 API,避免类型断言出错。
  4. interface 隔离:业务代码里把“依赖”抽象成 interface,测试时用 struct 嵌套 testify/mock 或 monkey patch 打桩。
  5. 并发隔离:每个用例重新 CreateTestContext,禁止把 *gin.Context 放到包级变量;mock 对象使用 testify/mock 的 Test(t) 方法自动注册 cleanup。
  6. 渲染断言:recorder.Body.Bytes() 可拿到真实返回;json 解码推荐用 json.Unmarshal 到匿名结构体,字段只写关心的部分,降低维护成本。

答案

下面给出一份可直接跑通、符合国内公司代码规范(gofmt、goimports、单行注释、驼峰命名)的完整示例。场景:订单接口需要调用 PayService 创建支付单,测试时把 PayService mock 掉。

// service/pay.go
package service

type PayService interface {
    Create(orderID string) (payURL string, err error)
}

// handler/order.go
package handler

import (
    "net/http"
    "github.com/gin-gonic/gin"
    "your_project/service"
)

const keyPayService = "svc.pay"

// 把依赖注入 context,方便测试时替换
func InjectPayService(c *gin.Context, svc service.PayService) {
    c.Set(keyPayService, svc)
}

// 从 context 取出依赖
func MustPayService(c *gin.Context) service.PayService {
    return c.MustGet(keyPayService).(service.PayService)
}

func CreateOrder(c *gin.Context) {
    orderID := c.Param("orderID")
    svc := MustPayService(c)
    payURL, err := svc.Create(orderID)
    if err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{"msg": err.Error()})
        return
    }
    c.JSON(http.StatusOK, gin.H{"payURL": payURL})
}

// handler/order_test.go
package handler

import (
    "net/http"
    "net/http/httptest"
    "testing"

    "github.com/gin-gonic/gin"
    "github.com/stretchr/testify/assert"
    "github.com/stretchr/testify/mock"
    "your_project/service"
)

// 1. 定义 mock 结构体
type mockPayService struct{ mock.Mock }

func (m *mockPayService) Create(orderID string) (string, error) {
    args := m.Called(orderID)
    return args.String(0), args.Error(1)
}

// 2. 测试函数
func TestCreateOrder_OK(t *testing.T) {
    gin.SetMode(gin.TestMode)

    // 2.1 构造 recorder & context
    w := httptest.NewRecorder()
    c, _ := gin.CreateTestContext(w)

    // 2.2 构造请求,绑定参数
    req := httptest.NewRequest(http.MethodPost, "/order/123456", nil)
    c.Request = req
    c.Params = gin.Params{{Key: "orderID", Value: "123456"}}

    // 2.3 注入 mock service
    m := new(mockPayService)
    m.On("Create", "123456").Return("https://mock.com/pay", nil)
    InjectPayService(c, m)

    // 2.4 执行
    CreateOrder(c)

    // 2.5 断言
    assert.Equal(t, http.StatusOK, w.Code)
    assert.JSONEq(t, `{"payURL":"https://mock.com/pay"}`, w.Body.String())
    m.AssertExpectations(t)
}

// 3. 异常分支单测
func TestCreateOrder_Fail(t *testing.T) {
    gin.SetMode(gin.TestMode)
    w := httptest.NewRecorder()
    c, _ := gin.CreateTestContext(w)
    c.Request = httptest.NewRequest(http.MethodPost, "/order/123", nil)
    c.Params = gin.Params{{Key: "orderID", Value: "123"}}

    m := new(mockPayService)
    m.On("Create", "123").Return("", assert.AnError)
    InjectPayService(c, m)

    CreateOrder(c)

    assert.Equal(t, http.StatusInternalServerError, w.Code)
    assert.Contains(t, w.Body.String(), assert.AnError.Error())
    m.AssertExpectations(t)
}

运行 go test ./handler -v,两条用例均通过,且用例之间零共享、零端口监听,CI 可直接跑。

拓展思考

  1. 如果依赖很多,手动写 InjectXXX 会爆炸,可以借助 fx 或 wire 做依赖注入,但测试时依旧要提供 mock 版本;
  2. 对中间件里的依赖(例如鉴权用的 JWT 解析器),同样用 interface + mock 思路,把“解析 token”抽象成接口,测试时注入返回固定 UID 的 mock;
  3. 当 handler 里需要读取私有字段(例如 gRPC 连接池),而 interface 不好拆时,可以用 monkey 补丁,但注意 monkey 只在 linux/darwin amd64 下生效,CI 要加条件编译;
  4. 如果团队追求 100% 单测覆盖率,建议把“渲染逻辑”拆出去做纯函数单测,把“依赖调用”拆出去做 mock 测试,两者分开后,每个函数都极易覆盖;
  5. 在集成阶段,再用 httptest 启动真实路由(gin.Default())并挂载所有中间件,做端到端冒烟,保证 mock 测试没漏掉主干路径。