Golang如何使用net/http/httptest模拟HTTP请求

答案:go的net/http/httptest包提供NewRecorder捕获响应、NewRequest构造请求、NewServer启动测试服务器,可用于单元和集成测试HTTP处理逻辑,支持GET、POST等请求模拟及状态码、响应体验证。

Golang如何使用net/http/httptest模拟HTTP请求

Go语言中,net/http/httptest包提供了非常方便的工具来测试HTTP服务器和处理程序。它允许你在不启动真实网络端口的情况下模拟HTTP请求和响应,非常适合单元测试。

创建一个简单的HTTP处理器用于测试

假设你有一个简单的HTTP处理函数:

 func helloHandler(w http.ResponseWriter, r *http.Request) {     fmt.Fprintf(w, "Hello, %s!", r.URL.Query().Get("name")) } 

你可以使用httptest.NewRecorder()来捕获响应,并用httptest.NewRequest()构造请求。

使用httptest.NewRequest和httptest.NewRecorder

下面是一个完整的测试示例:

立即学习go语言免费学习笔记(深入)”;

 func TestHelloHandler(t *testing.T) {     req := httptest.NewRequest("GET", "/?name=World", nil)     w := httptest.NewRecorder()      helloHandler(w, req)      resp := w.Result()     body, _ := io.ReadAll(resp.Body)      if string(body) != "Hello, World!" {         t.Errorf("期望 Hello, World!,实际得到 %s", string(body))     }      if resp.StatusCode != http.StatusOK {         t.Errorf("期望状态码 200,实际得到 %d", resp.StatusCode)     } } 

测试自定义的HTTP服务(使用 httptest.Server)

如果你想测试整个HTTP服务(包括路由中间件等),可以使用httptest.NewServer启动一个临时的本地服务器。

Golang如何使用net/http/httptest模拟HTTP请求

凹凸工坊-AI手写模拟器

AI手写模拟器,一键生成手写文稿

Golang如何使用net/http/httptest模拟HTTP请求225

查看详情 Golang如何使用net/http/httptest模拟HTTP请求

 func TestWithTestServer(t *testing.T) {     mux := http.NewServeMux()     mux.HandleFunc("/hi", func(w http.ResponseWriter, r *http.Request) {         fmt.Fprintf(w, "Hi there!")     })      server := httptest.NewServer(mux)     defer server.Close()      resp, err := http.Get(server.URL + "/hi")     if err != nil {         t.Fatal(err)     }     defer resp.Body.Close()      body, _ := io.ReadAll(resp.Body)     if string(body) != "Hi there!" {         t.Errorf("期望 Hi there!,实际得到 %s", string(body))     } } 

server.URL会自动分配一个可用的本地地址(如 http://127.0.0.1:xxxx),适合测试客户端逻辑或集成场景。

模拟POST请求并发jsON数据

对于POST请求,你需要设置请求体和Content-Type:

 func TestPostHandler(t *testing.T) {     payload := strings.NewReader(`{"message": "hello"}`)      req := httptest.NewRequest("POST", "/api/v1/message", payload)     req.Header.Set("Content-Type", "application/json")      w := httptest.NewRecorder()      messageHandler(w, req)      if w.Code != http.StatusCreated {         t.Errorf("期望状态码 201,实际得到 %d", w.Code)     } } 

这样可以完整测试API接口的行为,包括请求头、请求体和返回状态码

基本上就这些。使用httptest能让你写出高效、可靠的HTTP处理逻辑测试,无需依赖外部网络环境。关键在于理解NewRecorder用于捕获输出,NewRequest构造输入,而NewServer适用于需要完整HTTP服务的场景。

上一篇
下一篇
text=ZqhQzanResources