我一直在寻找答案,但找不到。我的问题是,是否可以测试依赖于动态 URL token 的处理函数?
例如,假设我的处理程序函数需要来自动态生成的 URL 的 token (我不知道 token 是如何生成的,除了 URL 参数之外我也无法访问它)。我的 URL 总是看起来像这样:www.example.com/?token=randomtokenhere
func TokenProcessing(w http.ResponseWriter, r *http.Request) {
token := r.URL.Query().Get("token") // dynamically generated from parsed URL
// code to do something with said token
}
是否可以在不访问 token 创建方式的情况下以某种方式对该处理程序函数进行单元测试?
最佳答案
您可以填充 http.Request
的查询参数,然后使用 httptest.ResponseRecorder
测试处理程序
例如
package main
import (
"log"
"net/http"
"net/http/httptest"
"testing"
)
// In this test file to keep the SO example concise
func TokenProcessing(w http.ResponseWriter, r *http.Request) {
token := r.URL.Query().Get("token") // dynamically generated from parsed URL
// code to do something with said token
log.Println(token)
}
func TestTokenProcessing(t *testing.T) {
rr := httptest.NewRecorder()
r, err := http.NewRequest("GET", "http://golang.org/", nil)
if err != nil {
t.Fatal(err)
}
// Generate suitable values here - e.g. call your generateToken() func
r.URL.Query().Add("token", "someval")
handler := http.HandlerFunc(TokenProcessing)
handler.ServeHTTP(rr, r)
if code := rr.Code; code != http.StatusOK {
t.Fatalf("handler did not return correct status: want %v got %v",
http.StatusOK, code)
}
// Test the rest of the response - i.e. sets a header, etc.
}
关于unit-testing - 在 Go 中测试依赖于动态 URL 的处理函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31888744/