我已经为此搜索了所有内容,但找不到任何东西。
我有一个结构体,它接收 ahttp.Client并发送几个 GET 请求。在我的测试中,我想模拟响应,因此它不会发送真正的请求。
目前我已经想出了如何只处理 1 个请求,如下所示:
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
file, err := os.Open("./testdata/1.html")
if err != nil {
t.Error(err)
}
bytes, err := ioutil.ReadAll(file)
if err != nil {
t.Error(err)
}
w.Write(bytes)
}))
ts.Client() // Now I can inject this client into my struct.
Run Code Online (Sandbox Code Playgroud)
因此,一旦该响应被模拟出来并且 http 客户端执行一个新请求,我的测试就会在此之后发送真正的请求。
如何允许多个处理程序,以便在调用时模拟多个响应http.Client.Get(...)?
ServeMux.Handle可用于设置服务器来处理多个请求,如本例所示。
package main
import (
"log"
"net/http"
)
const addr = "localhost:12345"
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/hello", HandleHello)
// other handlers can be assigned to separate paths
log.Printf("Now listening on %s...\n", addr)
server := http.Server{Handler: mux, Addr: addr}
log.Fatal(server.ListenAndServe())
}
func HandleHello(w http.ResponseWriter, r *http.Request) {
log.Printf("Hello!")
}
Run Code Online (Sandbox Code Playgroud)
但说实话,您可能只想抽象http.Client您创建的接口背后的内容,然后使用返回您想要的测试实现进行存根。通过这样做,您可以避免测试中 http 通信的开销。
小智 5
由于原始问题使用 httptest.NewServer - 您可以在 httptest.Server 函数上注册一个 ServeMux,然后您可以向该 mux 添加几个路由:
mux := http.NewServeMux()
mux.HandleFunc("/someroute/", func(res http.ResponseWriter, req *http.Request) {
...do some stuff...
})
mux.HandleFunc("/someotherroute/", func(res http.ResponseWriter, req *http.Request) {
...do other stuff...
})
ts := httptest.NewServer(mux)
defer ts.Close()
Run Code Online (Sandbox Code Playgroud)