单元测试:httptest + 表驱动测试 handler/中间件

给 Web 层写测试不必真的起服务:net/http/httptest 提供 NewRecorder(模拟 ResponseWriter)与 NewRequest(构造请求),配合 Gin 的 ServeHTTP 即可完整走一遍路由。概念以官方 testing、net/http/httptest 文档为准。

1. 最小测试用例

func HelloHandler(c *gin.Context) {
    c.JSON(http.StatusOK, gin.H{"msg": "hello " + c.Param("name")})
}

func TestHelloHandler(t *testing.T) {
    r := gin.New()
    r.GET("/hello/:name", HelloHandler)
    req := httptest.NewRequest(http.MethodGet, "/hello/gin", nil)
    rec := httptest.NewRecorder()
    r.ServeHTTP(rec, req) // 内部走完整路由
    if rec.Code != http.StatusOK {
        t.Fatalf("status = %d, want 200", rec.Code)
    }
    var got map[string]string
    json.Unmarshal(rec.Body.Bytes(), &got) // 反序列化 JSON 断言
    if got["msg"] != "hello gin" {
        t.Fatalf("msg = %q", got["msg"])
    }
}

2. 表驱动 + 子测试

func TestCheckAge(t *testing.T) {
    cases := []struct {
        name string
        age  int
        want int // 期望状态码
    }{
        {"成年", 20, 200},
        {"未成年", 15, 400},
        {"缺失参数", -1, 400},
    }
    for _, tc := range cases {
        t.Run(tc.name, func(t *testing.T) {
            target := "/check"
            if tc.age >= 0 {
                target = fmt.Sprintf("/check?age=%d", tc.age)
            }
            rec := httptest.NewRecorder()
            newRouter().ServeHTTP(rec,
                httptest.NewRequest(http.MethodGet, target, nil))
            if rec.Code != tc.want {
                t.Errorf("age=%d code=%d want=%d", tc.age, rec.Code, tc.want)
            }
        })
    }
}

3. 带 body 的请求

body := strings.NewReader(`{"title":"demo"}`)
req := httptest.NewRequest(http.MethodPost, "/api/todos", body)
req.Header.Set("Content-Type", "application/json")

4. 测试中间件

func TestAuthRequired(t *testing.T) {
    called := false
    r := gin.New()
    r.GET("/secret", AuthRequired(), func(c *gin.Context) {
        called = true
        c.JSON(http.StatusOK, gin.H{"uid": c.GetUint("userID")})
    })
    rec := httptest.NewRecorder()
    r.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/secret", nil))
    if rec.Code != http.StatusUnauthorized || called {
        t.Fatal("无 Token 应 401 且不进入 handler")
    }
}

注意点

  • DAO 与外部依赖用接口注入 fake,单测别连真的 MySQL/Redis。
  • 用例名要能说明意图;时间断言用 before/after,不要精确相等。
  • 执行:go test ./...;怀疑数据竞争时加 -race

小结

httptest 三件套——NewRequest、NewRecorder、ServeHTTP——就能覆盖 handler 与中间件。配合表驱动与接口注入 fake,路由层测试又快又稳,实战章节的「测试要点」会直接复用这套写法。

笔记加载中…