使用httptest可无需启动服务器测试HTTP Handler。1. 用httptest.NewRequest创建请求;2. 用httptest.NewRecorder记录响应;3. 调用Handler并验证状态码、响应体等。支持查询参数、路径参数、POST数据及Header、Cookie、重定向检查,需覆盖各类状态码与边界情况。
在Golang中对HTTP Handler进行单元测试,关键在于使用 net/http/httptest 包模拟HTTP请求和响应。通过创建测试用的请求(*http.Request)和记录响应(*httptest.ResponseRecorder),你可以验证Handler的行为是否符合预期,而无需启动真实服务器。
使用 httptest 模拟请求和响应
Go标准库中的 httptest 提供了简便的方式来测试Handler函数。你不需要运行服务器,只需构造一个请求,调用Handler,然后检查返回结果。
基本步骤如下:
- 使用 httptest.NewRequest() 创建一个模拟的 *http.Request
- 使用 httptest.NewRecorder() 获取一个 *ResponseRecorder 来捕获响应
- 直接调用你的Handler函数,传入 ResponseRecorder 和 Request
- 检查 ResponseRecorder 中的状态码、响应体等字段
func TestHelloHandler(t *testing.T) {
req := httptest.NewRequest("GET", "/hello", nil)
w := httptest.NewRecorder()
HelloHandler(w, req)
resp := w.Result()
body, _ := io.ReadAll(resp.Body)
if resp.StatusCode != http.StatusOK {
t.Errorf("expected status 200, got %d", resp.StatusCode)
}
if string(body) != "Hello, World!" {
t.Errorf("expected body 'Hello, World!', got '%s'", string(body))
}
}
测试带路径参数或查询参数的Handler
如果Handler依赖URL路径参数或查询字符串,你需要在构造请求时正确设置URL。
例如,测试一个接收查询参数的Handler:
func TestSearchHandler(t *testing.T) {
req := httptest.NewRequest("GET", "/search?q=golang", nil)
w := httptest.NewRecorder()
SearchHandler(w, req)
if w.Code != http.StatusOK {
t.Errorf("expected 200, got %d", w.Code)
}
}
对于使用第三方路由库(如 gorilla/mux)处理路径参数的情况,需在测试中显式设置URL变量:
req := httptest.NewRequest("GET", "/user/123", nil)
ctx := context.WithValue(req.Context(), "user_id", "123")
req = req.WithContext(ctx)
或者更推荐的方式是,在测试中使用实际的mux路由器来确保路由行为一致。
测试POST请求与JSON数据
测试提交JSON数据的POST请求时,需要设置正确的Content-Type头,并提供请求体。
func TestCreateUser(t *testing.T) {
payload := `{"name": "Alice"}`
req := httptest.NewRequest("POST", "/users", strings.NewReader(payload))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
CreateUserHandler(w, req)
if w.Code != http.StatusCreated {
t.Errorf("expected 201, got %d", w.Code)
}
var user User
json.Unmarshal(w.Body.Bytes(), &user)
if user.Name != "Alice" {
t.Errorf("expected name Alice, got %s", user.Name)
}
}
验证Header、Cookie和重定向
ResponseRecorder 也支持检查响应头、Set-Cookie 和重定向目标。
比如验证是否设置了特定Header:
if w.Header().Get("X-App-Version") != "1.0.0" {
t.Error("missing or wrong version header")
}
检查重定向目标:
if w.Header().Get("Location") != "/login" {
t.Errorf("expected redirect to /login")
}
基本上就这些。只要把Handler当作普通函数调用,配合 httptest 工具构造输入输出,就能写出可靠、快速的单元测试。不复杂但容易忽略的是:确保覆盖不同状态码、错误路径和边界情况。









