登录
推荐 文章 Go 技术 课程 下载 专题 AI
首页 >  Golang >  Go教程

为 HTTP Handler 构造无网络依赖的请求与响应断言

来源:17golang原创

时间:2026-10-07 10:03:26 304浏览 收藏

测试 HTTP Handler 不需要先启动一个监听端口。把它当成接收 *http.Request、写入 http.ResponseWriter 的函数,用 httptest.NewRequest 构造请求,再用 httptest.NewRecorder 接住响应,就能在没有网络依赖的情况下稳定断言状态码、Header 和 Body。

官方资料:https://pkg.go.dev/net/http/httptest

要点速览
  • 单元测试优先直接调用 Handler,不必创建真实服务器。
  • 响应完成后用 recorder.Result() 读取快照,Header 与 Body 的语义更接近真实响应。
  • 成功、参数错误和空结果应放进同一组表格驱动用例,边界才不会被遗漏。

把 Handler 测试边界收窄为一次函数调用

如果目标只是验证路由函数对输入的处理,直接调用 Handler 比启动 httptest.NewServer 更合适。前者不经过端口、DNS、客户端重试和序列化链路,失败时能更快定位到请求解析或响应构造本身。真正需要验证中间件链、TLS、重定向或客户端行为时,再升级到测试服务器。

下面的示例让 Handler 只关心一个查询参数,并把错误分支也设计成明确的 HTTP 响应:

package handler_test

import (
    "fmt"
    "net/http"
)

// greetHandler 只演示 Handler 的输入与输出边界,不访问外部网络。
func greetHandler(w http.ResponseWriter, r *http.Request) {
    name := r.URL.Query().Get("name")
    if name == "" {
        http.Error(w, "missing name", http.StatusBadRequest)
        return
    }
    // 显式设置类型,测试时可以断言 Header 是否在首次写入前完成。
    w.Header().Set("Content-Type", "text/plain; charset=utf-8")
    fmt.Fprintf(w, "hello, %s", name)
}

用 httptest.NewRequest 固定请求输入

httptest.NewRequest 生成的是适合传给服务端 Handler 的请求。测试中可以直接把查询参数写入 target,也可以补充 Header 和 Body;这样每个用例都能从代码看出自己的输入,不依赖运行环境。

func TestGreetHandler(t *testing.T) {
    // 查询参数放在 URL 中,输入与真实 HTTP 请求保持同一表达方式。
    req := httptest.NewRequest(http.MethodGet, "/greet?name=Go", nil)
    req.Header.Set("Accept", "text/plain")

    recorder := httptest.NewRecorder()
    greetHandler(recorder, req)
}

无请求体时传入 nil 即可;需要测试 JSON 或表单时,用 strings.NewReader 提供 body,并同步设置 Content-Type。如果 Handler 读取上下文取消、租户标识等信息,可使用 httptest.NewRequestWithContext 把上下文作为输入的一部分。

Go httptest.NewRequest 将方法、路径查询参数和 Header 组合成 Handler 输入的结构说明图
图1:请求输入结构说明图,展示 httptest.NewRequest 与 Handler 的无网络调用边界。

用 ResponseRecorder 断言状态、Header 与 Body

ResponseRecorder 实现了 http.ResponseWriter,可以接住 Handler 写入的内容。调用完成后建议使用 Result() 得到 *http.Response 再断言;官方文档特别提醒,直接读取 Code 在 Handler 从未写入时可能得到 0,而 Result() 更适合获取隐含的 200 状态。

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

func TestGreetHandlerResponse(t *testing.T) {
    req := httptest.NewRequest("GET", "/greet?name=Go", nil)
    recorder := httptest.NewRecorder()

    // 直接调用一次 Handler,整个测试不需要真实端口或外部服务。
    greetHandler(recorder, req)
    resp := recorder.Result()
    defer resp.Body.Close() // 读取完响应体后释放资源。

    if resp.StatusCode != http.StatusOK {
        t.Fatalf("status = %d, want %d", resp.StatusCode, http.StatusOK)
    }
    if got := resp.Header.Get("Content-Type"); got != "text/plain; charset=utf-8" {
        t.Fatalf("content type = %q", got)
    }
    body, err := io.ReadAll(resp.Body)
    if err != nil {
        t.Fatalf("read response body: %v", err)
    }
    if string(body) != "hello, Go" {
        t.Fatalf("body = %q", body)
    }
}

这里的断言顺序是状态、Header、Body:状态先确认请求走到了预期分支,Header 验证响应类型,Body 最后验证业务结果。不要对整个 http.Response 做深度相等比较,因为响应对象未来可能包含更多字段;逐项断言反而更能表达测试意图。

Go ResponseRecorder.Result 返回状态码 Header 和 Body 供测试断言的结构说明图
图2:响应断言结构说明图,展示 Handler 输出经过 ResponseRecorder 后按字段读取。

用表格驱动覆盖成功、错误和边界输入

单个成功用例只能说明“正常输入能工作”。把缺少参数、普通参数和包含空格的参数放入表格,测试代码就能用同一套流程覆盖多个边界:

func TestGreetHandlerCases(t *testing.T) {
    tests := []struct {
        name       string
        target     string
        wantStatus int
        wantBody   string
    }{
        {name: "missing query", target: "/greet", wantStatus: http.StatusBadRequest, wantBody: "missing name\n"},
        {name: "normal query", target: "/greet?name=Go", wantStatus: http.StatusOK, wantBody: "hello, Go"},
    }

    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            // 每个子测试都创建独立请求和 recorder,避免状态互相污染。
            req := httptest.NewRequest(http.MethodGet, tt.target, nil)
            recorder := httptest.NewRecorder()
            greetHandler(recorder, req)

            resp := recorder.Result()
            defer resp.Body.Close()
            body, err := io.ReadAll(resp.Body)
            if err != nil {
                t.Fatalf("read response body: %v", err)
            }
            if resp.StatusCode != tt.wantStatus || string(body) != tt.wantBody {
                t.Fatalf("got status=%d body=%q, want status=%d body=%q", resp.StatusCode, body, tt.wantStatus, tt.wantBody)
            }
        })
    }
}
检查项推荐断言常见边界
状态resp.StatusCode200、400、404、405
Headerresp.Header.Get类型、缓存、位置
Bodyio.ReadAll 后解析空体、错误 JSON、换行

常见问题与维护边界

什么时候应该改用 httptest.NewServer?

当测试重点变成真实客户端如何访问 Handler、重定向、Cookie、TLS 或中间件组合时,使用 httptest.NewServer 更接近端到端链路。只验证单个 Handler 的输入输出时,Recorder 更轻量。

为什么不直接读取 ResponseRecorder.Code?

Handler 没有调用 WriteHeader 或 Write 时,Recorder 的内部状态可能仍是 0;调用 Result() 后读取 StatusCode,才能得到符合 HTTP 语义的响应快照。

测试响应体后需要关闭 Body 吗?

需要。测试中也应在得到响应后 defer resp.Body.Close(),让代码习惯与生产客户端保持一致;然后运行 go test ./... 检查全部包。

声明:本文转载于:17golang原创 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>