如何用 Golang 测试 HTTP API_Golang 请求模拟与响应验证方法

使用 httptest 可高效测试 Golang HTTP API。1. 用 NewRecorder 模拟请求并检查状态码、响应体和头信息;2. 测试路由和中间件时将 ServeMux 注入测试;3. 用 NewServer 启动临时服务进行端到端验证。

测试 HTTP API 是构建可靠服务的关键环节。在 Golang 中,你可以使用标准库中的 net/http/httptest 包来模拟 HTTP 请求并验证响应,无需启动真实服务器。这种方式快速、安全,适合单元测试和集成测试。

使用 httptest 模拟 HTTP 服务器

httptest 提供了 NewRecorderNewServer 两个核心工具:

  • NewRecorder():创建一个 http.ResponseWriter 的记录器,用于捕获响应内容
  • NewServer():启动一个临时的本地 HTTP 服务,用于端到端测试

下面是一个简单的例子,测试一个返回 JSON 的 API:

package main

import (
    "encoding/json"
    "net/http"
    "net/http/httptest"
    "testing"
)

func handler(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(map[string]string{"message": "Hello, World!"})
}

func TestAPIHandler(t *testing.T) {
    req := httptest.NewRequest("GET", "/", nil)
    rec := httptest.NewRecorder()

    handler(rec, req)

    if rec.Code != http.StatusOK {
        t.Errorf("期望状态码 %d,实际得到 %d", http.StatusOK, rec.Code)
    }

    expected := `{"message":"Hello, World!"}`
    if rec.Body.String() != expected {
        t.Errorf("响应体不匹配:期望 %s,实际 %s", expected, rec.Body.String())
    }
}

验证响应头与状态码

真实的 API 往往依赖特定的响应头(如 Content-Type、Authorization 等)。你可以在测试中精确检查这些字段:

if contentType := rec.Header().Get("Content-Type"); contentType != "application/json" {
    t.Errorf("期望 Content-Type 为 application/json,实际为 %s", contentType)
}

同时确保状态码符合预期,比如创建资源时应返回 201:

if rec.Code != http.StatusCreated {
    t.Errorf("期望状态码 201,实际 %d", rec.Code)
}

测试路由与中间件行为

如果你使用的是 Gin、Echo 或标准的 http.ServeMux,可以将整个路由结构注入测试:

func setupRouter() *http.ServeMux {
    mux := http.NewServeMux()
    mux.HandleFunc("/api/v1/hello", handler)
    return mux
}

func TestRoutePath(t *testing.T) {
    req := httptest.NewRequest("GET", "/api/v1/hello", nil)
    rec := httptest.NewRecorder()

    setupRouter().ServeHTTP(rec, req)

    if rec.Code != http.StatusOK {
        t.FailNow()
    }
}

这种方法也适用于测试中间件,例如身份验证或日志记录逻辑。

发送真实请求并验证外部行为(可选)

若需测试完整网络栈,可用 httptest.NewServer 启动临时服务:

server := httptest.NewServer(http.HandlerFunc(handler))
defer server.Close()

resp, err := http.Get(server.URL)
if err != nil {
    t.Fatal(err)
}
defer resp.Body.Close()

if resp.StatusCode != http.StatusOK {
    t.Errorf("期望 200,实际 %d", resp.StatusCode)
}

这种方式更贴近真实环境,适合集成测试。

基本上就这些。通过组合使用 httptest 和标准断言,你能高效地覆盖大多数 API 测试场景,保证接口稳定性和正确性。