Go / 系统课时
单元测试 HTTP 处理器
单元测试 HTTP 处理器
HTTP 处理器的大多数协议行为都能在内存中验证,无需启动真实监听端口。本节用 httptest 构造请求和记录响应,再用表驱动用例同时检查成功路径、参数校验、边界值、状态码、响应头与响应体。
学习目标
- 使用
httptest在内存中构造请求并捕获http.Handler的响应 - 用表驱动测试覆盖成功、参数缺失和长度边界
- 同时验证状态码、响应类型和响应体,避免只检查测试是否报错
用内存请求驱动处理器
下面将最小处理器和测试放在同一个 handler_test.go 中,便于直接运行。处理器要求查询参数 name 去除首尾空白后包含 1~20 个 Unicode 字符;测试直接调用函数,不创建 TCP 监听器。
go
package handler
import (
"encoding/json"
"net/http"
testhttp "net/http/httptest"
"strings"
"testing"
"unicode/utf8"
)
const jsonContentType = "application/json"
func greetHandler(w http.ResponseWriter, r *http.Request) {
name := strings.TrimSpace(r.URL.Query().Get("name"))
if name == "" || utf8.RuneCountInString(name) > 20 {
http.Error(w, "invalid name", http.StatusBadRequest)
return
}
w.Header().Set("Content-Type", jsonContentType)
_ = json.NewEncoder(w).Encode(map[string]string{
"message": "hello " + name,
})
}
type greetCase struct {
name string
target string
wantStatus int
wantBody string
}
func TestGreetHandler(t *testing.T) {
cases := []greetCase{
{"success", "/greet?name=Go", http.StatusOK, `{"message":"hello Go"}` + "\n"},
{"missing name", "/greet", http.StatusBadRequest, "invalid name\n"},
{"too long", "/greet?name=abcdefghijklmnopqrstu", http.StatusBadRequest, "invalid name\n"},
{"max length", "/greet?name=abcdefghijklmnopqrst", http.StatusOK, `{"message":"hello abcdefghijklmnopqrst"}` + "\n"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
request := testhttp.NewRequest(http.MethodGet, tc.target, nil)
recorder := testhttp.NewRecorder()
// 直接调用处理器,只验证 HTTP 输入输出边界。
greetHandler(recorder, request)
response := recorder.Result()
defer response.Body.Close()
if response.StatusCode != tc.wantStatus {
t.Fatalf("status = %d, want %d", response.StatusCode, tc.wantStatus)
}
if recorder.Body.String() != tc.wantBody {
t.Fatalf("body = %q, want %q", recorder.Body.String(), tc.wantBody)
}
// 成功分支还必须满足约定的 JSON 响应类型。
if tc.wantStatus == http.StatusOK && response.Header.Get("Content-Type") != jsonContentType {
t.Fatalf("Content-Type = %q, want %q", response.Header.Get("Content-Type"), jsonContentType)
}
})
}
}在包含该文件的 Go 模块目录运行测试:
bash
go test -v预期输出:
text
=== RUN TestGreetHandler
=== RUN TestGreetHandler/success
=== RUN TestGreetHandler/missing_name
=== RUN TestGreetHandler/too_long
=== RUN TestGreetHandler/max_length
--- PASS: TestGreetHandler (<TIME>)
--- PASS: TestGreetHandler/success (<TIME>)
--- PASS: TestGreetHandler/missing_name (<TIME>)
--- PASS: TestGreetHandler/too_long (<TIME>)
--- PASS: TestGreetHandler/max_length (<TIME>)
PASS
ok <PATH> <TIME><TIME> 和 <PATH> 分别代表实际运行耗时和当前包的模块路径,不同机器上的值会不同。
ResponseRecorder 能验证什么
NewRecorder 返回的记录器实现了 http.ResponseWriter,会保存处理器写出的状态码、响应头和响应体。调用 Result() 后可以按 *http.Response 的方式检查状态和头字段,而 recorder.Body 适合直接比较响应体。
对这种只关心单个 Handler 输入输出的测试,内存记录器已经覆盖客户端可观察到的关键协议行为。没有路由、网络或真实服务依赖时,额外启动测试服务器只会增加测试链路和故障来源。
用表驱动测试守住边界
表驱动测试把输入和期望集中在一组用例中。本例同时验证缺少参数、21 个字符和恰好 20 个字符,能及时发现 < 20、<= 21 等边界判断错误。新增规则时通常只需要补充用例,而不必复制整段测试流程。
什么时候再启动测试服务器
当目标是验证完整路由、中间件链、Cookie 或重定向行为,或者被测对象本身是一个会主动发送 HTTP 请求的客户端时,httptest.NewServer 才更合适。单个处理器的状态码、响应头和响应体校验直接调用 Handler,测试会更快、更确定,也不依赖真实端口。
按自己的节奏,确认真正理解。