使用 httptest 可轻松测试 Go HTTP 接口。1. 通过 NewRequest 和 NewRecorder 模拟请求与响应,验证处理函数输出;2. 结合 Gin 等框架的 ServeHTTP 方法测试路由与中间件;3. 测试 JSON 接口时检查 Content-Type 头部并解析响应体;4. 使用表驱动测试多种输入、覆盖错误路径;5. 利用 t.Run 分组子测试提升可读性。无需外部依赖即可高效完成接口测试。

测试 HTTP 接口是 Go 项目开发中的常见任务。Go 标准库提供了 net/http/httptest 包,结合 testing 包,可以轻松构建高效、可靠的接口测试。下面介绍几种常用方法和实用技巧。
使用 httptest 模拟 HTTP 服务
在单元测试中,我们通常不希望依赖真实网络请求。httptest 可以创建一个临时的 HTTP 服务器,用于测试处理函数。
例如,测试一个简单的 GET 接口:
func handler(w http.ResponseWriter, r *http.Request) {fmt.Fprintf(w, "Hello, %s!", r.URL.Query().Get("name"))
}
func TestHandler(t *testing.T) {
req := httptest.NewRequest("GET", "/?name=world", nil)
w := httptest.NewRecorder()
handler(w, req)
resp := w.Result()
body, _ := io.ReadAll(resp.Body)
if string(body) != "Hello, world!" {
t.Errorf("expected Hello, world!, got %s", string(body))
}
}
测试路由和中间件(如 Gin、Echo 等框架)
如果你使用的是 Web 框架(如 Gin),可以用其提供的测试工具配合 httptest。
立即学习“go语言免费学习笔记(深入)”;
以 Gin 为例:
func setupRouter() *gin.Engine {r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
c.String(200, "pong")
})
return r
}
func TestPingRoute(t *testing.T) {
r := setupRouter()
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/ping", nil)
r.ServeHTTP(w, req)
if w.Code != 200 {
t.Errorf("status code is %d", w.Code)
}
if w.Body.String() != "pong" {
t.Errorf("body should be pong")
}
}
关键点是使用 ServeHTTP 方法将请求发送给路由引擎,并通过 httptest.ResponseRecorder 捕获响应。
测试 JSON 请求与响应
大多数 API 返回 JSON 数据,测试时需要验证结构和内容。
示例:测试一个返回 JSON 的接口
func jsonHandler(w http.ResponseWriter, r *http.Request) {w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{"message": "ok"})
}
func TestJSONHandler(t *testing.T) {
req := httptest.NewRequest("GET", "/", nil)
w := httptest.NewRecorder()
jsonHandler(w, req)
var data map[string]string
json.Unmarshal(w.Body.Bytes(), &data)
if data["message"] != "ok" {
t.Errorf("expected ok, got %s", data["message"])
}
if w.Header().Get("Content-Type") != "application/json" {
t.Errorf("content-type header missing")
}
}
注意检查 Content-Type 头部和 JSON 解码是否成功。
实用技巧
- 复用测试请求:使用 httptest.NewRequest 可以设置 Body、Header、Query 参数,模拟各种输入场景。
- 测试错误路径:比如传入非法参数,检查是否返回 400 或对应错误信息。
- 表驱动测试:对多个输入输出组合使用表格形式测试,提升覆盖率。
- 避免 sleep 或超时等待:保持测试快速、确定性。
- 使用 t.Run 分组子测试:让输出更清晰,便于定位问题。
基本上就这些。Go 的测试机制简洁直接,配合 httptest 能覆盖大部分 HTTP 接口测试需求,无需额外重型框架。关键是写好断言,模拟全面场景。










