答案:使用 net/http/httptest 可创建模拟服务器或直接测试处理器。示例包括用 httptest.NewServer 测试完整请求响应流程,或用 httptest.NewRequest 和 NewRecorder 直接调用 Handler 验证状态码、JSON 响应体及头部信息,支持 GET、POST 等多种请求类型,确保接口行为正确且可重复验证。

在Golang中测试HTTP请求并验证响应,通常使用 net/http/httptest 包来创建模拟的HTTP服务端,然后通过标准的HTTP客户端发起请求并检查返回结果。这种方式无需启动真实服务器,安全、快速且易于控制。
使用 httptest 创建测试服务器
你可以用 httptest.NewServer 启动一个临时的HTTP服务器,它会在本地随机端口运行,并在测试结束后自动关闭。
示例:测试一个返回 JSON 的 handler
func helloHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json");
json.NewEncoder(w).Encode(map[string]string{"message": "Hello, World!"})
}
func TestHelloHandler(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(helloHandler))
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("expected status %d, got %d", http.StatusOK, resp.StatusCode)
}
var data map[string]string
if err := json.NewDecoder(resp.Body).Decode(&data); err != nil {
t.Fatalf("failed to decode JSON: %v", err)
}
if msg, exists := data["message"]; !exists || msg != "Hello, World!" {
t.Errorf(`expected message "Hello, World!", got "%s"`, msg)
}
}
直接测试 Handler 函数(不启动服务器)
如果你只想测试一个 http.HandlerFunc,可以不用启动完整服务器,而是使用 httptest.NewRequest 和 httptest.NewRecorder 来模拟请求和记录响应。
立即学习“go语言免费学习笔记(深入)”;
func TestHelloHandler_UnitStyle(t *testing.T) {
req := httptest.NewRequest("GET", "/", nil)
recorder := httptest.NewRecorder()
handler := http.HandlerFunc(helloHandler)
handler.ServeHTTP(recorder, req)
if recorder.Code != http.StatusOK {
t.Errorf("expected status %d, got %d", http.StatusOK, recorder.Code)
}
var data map[string]string
if err := json.Unmarshal(recorder.Body.Bytes(), &data); err != nil {
t.Fatalf("failed to unmarshal response: %v", err)
}
if msg, exists := data["message"]; !exists || msg != "Hello, World!" {
t.Errorf(`expected message "Hello, World!", got "%s"`, msg)
}
}
验证响应头、状态码和错误处理
除了响应体,你也可以检查响应头、内容类型、重定向等信息。
例如:
-
recorder.Code 获取状态码
-
recorder.Header().Get("Content-Type") 检查响应头
- 构造带参数或 Body 的请求,测试不同路径或方法
示例:测试 POST 请求和 Content-Type
func TestPostHandler(t *testing.T) {
body := strings.NewReader(`{"name": "Alice"}`)
req := httptest.NewRequest("POST", "/users", body)
req.Header.Set("Content-Type", "application/json")
recorder := httptest.NewRecorder()
http.HandlerFunc(userHandler).ServeHTTP(recorder, req)
if recorder.Code != http.StatusCreated {
t.Errorf("expected %d, got %d", http.StatusCreated, recorder.Code)
}
if ct := recorder.Header().Get("Content-Type"); ct != "application/json" {
t.Errorf("expected Content-Type application/json, got %s", ct)
}
}
基本上就这些。使用 httptest 可以灵活地测试各种HTTP行为,无论是简单接口还是复杂逻辑,都能通过构造请求、捕获响应来完整验证。关键是保持测试独立、可重复,并覆盖常见状态和边界情况。
以上就是如何在Golang中测试HTTP请求并验证响应的详细内容,更多请关注php中文网其它相关文章!