我有一些中间件,可以在请求中添加带有请求ID的上下文。
func AddContextWithRequestID(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var ctx context.Context
ctx = NewContextWithRequestID(ctx, r)
next.ServeHTTP(w, r.WithContext(ctx))
})}
如何为此编写测试?
答案 0 :(得分:1)
要进行测试,您需要运行传入请求的处理程序,并使用一个自定义next
处理程序来检查请求是否确实被修改。
您可以如下创建该处理程序:
(我假设您的NewContextWithRequestID
向请求中添加了一个“ reqId”键,其值为“ 1234”,您当然应该根据需要修改断言)
// create a handler to use as "next" which will verify the request
nextHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
val := r.Context().Value("reqId")
if val == nil {
t.Error("reqId not present")
}
valStr, ok := val.(string)
if !ok {
t.Error("not string")
}
if valStr != "1234" {
t.Error("wrong reqId")
}
})
然后您可以将该处理程序用作您的next
:
// create the handler to test, using our custom "next" handler
handlerToTest := AddContextWithRequestID(nextHandler)
然后调用该处理程序:
// create a mock request to use
req := httptest.NewRequest("GET", "http://testing", nil)
// call the handler using a mock response recorder (we'll not use that anyway)
handlerToTest.ServeHTTP(httptest.NewRecorder(), req)
将所有内容放在一起作为工作测试,这就是下面的代码。
注意:我修复了您原始的“ AddContextWithRequestID”中的一个小错误,因为当您未经初始化就声明时,ctx
值以nil
开头。
import (
"net/http"
"context"
"testing"
"net/http/httptest"
)
func NewContextWithRequestID(ctx context.Context, r *http.Request) context.Context {
return context.WithValue(ctx, "reqId", "1234")
}
func AddContextWithRequestID(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var ctx = context.Background()
ctx = NewContextWithRequestID(ctx, r)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
func TestIt(t *testing.T) {
// create a handler to use as "next" which will verify the request
nextHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
val := r.Context().Value("reqId")
if val == nil {
t.Error("reqId not present")
}
valStr, ok := val.(string)
if !ok {
t.Error("not string")
}
if valStr != "1234" {
t.Error("wrong reqId")
}
})
// create the handler to test, using our custom "next" handler
handlerToTest := AddContextWithRequestID(nextHandler)
// create a mock request to use
req := httptest.NewRequest("GET", "http://testing", nil)
// call the handler using a mock response recorder (we'll not use that anyway)
handlerToTest.ServeHTTP(httptest.NewRecorder(), req)
}