You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Go中测试http.NewRequest?附postJson函数测试需求

如何测试Go语言中的postJson函数

刚好我之前也处理过类似的测试场景,用Go标准库的httptest就能完美解决你的需求,不用额外依赖第三方工具。核心思路是创建一个模拟的HTTP服务器,让你的postJson函数向这个模拟服务器发送请求,我们就能在服务器端捕获并验证请求的所有细节(请求方法、头信息、POST数据)。

下面是完整的测试示例,我会一步步解释:

完整测试代码

package yourpackage // 替换成你的包名

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

// 你的postJson函数(这里直接复制过来方便测试)
func postJson(url string, jsonData []byte) error {
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
	if err != nil {
		return err
	}
	req.Header.Set("Content-Type", "application/json")
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close() // 建议加上defer,防止资源泄漏
	return nil
}

func TestPostJson(t *testing.T) {
	// 1. 定义我们要发送的测试JSON数据
	testData := map[string]string{
		"name": "test",
		"age":  "20",
	}
	jsonData, err := json.Marshal(testData)
	if err != nil {
		t.Fatalf("Failed to marshal test data: %v", err)
	}

	// 2. 创建模拟HTTP服务器
	testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// 验证请求方法是否为POST
		if r.Method != http.MethodPost {
			t.Errorf("Expected POST request, got %s", r.Method)
		}

		// 验证Content-Type头是否正确
		contentType := r.Header.Get("Content-Type")
		if contentType != "application/json" {
			t.Errorf("Expected Content-Type: application/json, got %s", contentType)
		}

		// 验证POST的JSON数据是否和我们发送的一致
		var receivedData map[string]string
		if err := json.NewDecoder(r.Body).Decode(&receivedData); err != nil {
			t.Fatalf("Failed to decode request body: %v", err)
		}
		if receivedData["name"] != testData["name"] || receivedData["age"] != testData["age"] {
			t.Errorf("Received data mismatch: expected %v, got %v", testData, receivedData)
		}

		// 返回一个成功响应
		w.WriteHeader(http.StatusOK)
	}))
	defer testServer.Close() // 测试结束后关闭服务器

	// 3. 调用我们的postJson函数,传入模拟服务器的URL
	err = postJson(testServer.URL, jsonData)
	if err != nil {
		t.Fatalf("postJson failed: %v", err)
	}
}

关键部分解释

  • 模拟服务器:httptest.NewServer会启动一个真实的HTTP服务器(在本地随机端口),我们通过testServer.URL获取它的地址。服务器的HandlerFunc就是我们的验证逻辑,所有发送到这个服务器的请求都会经过这个函数处理。
  • 请求验证:在HandlerFunc里,我们可以检查请求的方法、头信息,甚至解析请求体来验证POST的数据是否正确。如果任何验证失败,就用t.Errorf或t.Fatalf标记测试失败。
  • 资源清理:用defer testServer.Close()确保测试结束后关闭服务器,避免资源泄漏;另外建议在你的postJson函数里给resp.Body.Close()加上defer,这是Go里处理HTTP响应的最佳实践。

运行测试的话,直接在终端执行:

go test -v

如果所有验证都通过,测试就会成功;如果有任何不符合预期的地方,测试会输出具体的错误信息。

内容的提问来源于stack exchange,提问作者user9180311

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:26:19