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

测试 HTTP API 是构建可靠服务的关键环节。在 Golang 中,你可以使用标准库中的 net/http/httptest 包来模拟 HTTP 请求并验证响应,无需启动真实服务器。这种方式快速、安全,适合单元测试和集成测试。
httptest 提供了 NewRecorder 和 NewServer 两个核心工具:
下面是一个简单的例子,测试一个返回 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 等)。你可以在测试中精确检查这些字段:
立即学习“go语言免费学习笔记(深入)”;
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 测试场景,保证接口稳定性和正确性。
以上就是如何用 Golang 测试 HTTP API_Golang 请求模拟与响应验证方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号