httptest Recorder Tests A Handler

Drive an http.HandlerFunc with httptest.NewRequest and a response recorder so handler logic, headers, and error paths run without opening a listener.

GoData Fetching

Code

gosnippet
35 lines
package main

import (
	"encoding/json"
	"fmt"
	"net/http"
	"net/http/httptest"
)

// greetHandler 是业务代码,不知道自己在被测试
func greetHandler(w http.ResponseWriter, r *http.Request) {
	name := r.URL.Query().Get("name")
	if name == "" {
		http.Error(w, "name is required", http.StatusBadRequest)
		return
	}
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(map[string]string{"greeting": "hello " + name})
}

func main() {
	// Recorder 收集响应:不开监听端口就能完整执行 handler
	rec := httptest.NewRecorder()
	req := httptest.NewRequest(http.MethodGet, "/greet?name=ada", nil)
	greetHandler(rec, req)

	fmt.Println("status:", rec.Code)
	fmt.Println("content-type:", rec.Header().Get("Content-Type"))
	fmt.Println("body:", rec.Body.String())

	// 缺参路径:状态码与错误体同样可断言
	bad := httptest.NewRecorder()
	greetHandler(bad, httptest.NewRequest(http.MethodGet, "/greet", nil))
	fmt.Println("missing name:", bad.Code, bad.Body.String())
}

What the code does

The operative core is the functions greetHandler and main — everything else is wiring.

Watch out for

  • Nothing needs declaring — the runtime ships every API this handler test uses.

Applying it

Entry point, spelled out: func greetHandler(w http.ResponseWriter, r *http.Request)

The run emits 4 labeled sections — status:, content-type:, body:, missing name: — one per step.

Execute the file and main walks through greetHandler, in that order.

Statements that carry the logic

func greetHandler(w http.ResponseWriter, r *http.Request) {
	name := r.URL.Query().Get("name")
	if name == "" {
		http.Error(w, "name is required", http.StatusBadRequest)
		return
	}
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(map[string]string{"greeting": "hello " + name})
}

Interactive Tools for This Topic

FAQ

What does httptest Recorder Tests A Handler print when run?
Execute the whole file; each printed line is prefixed with a label like `status:`, `content-type:`, `body:`.