go - 使用 httptest 为多个处理程序提供服务以模拟多个请求

标签 go

我已经用谷歌搜索了所有内容,但找不到任何东西。

我有一个接受 http.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.

因此,一旦该响应被模拟出来并且 http 客户端执行新请求,我的测试就会在此之后发送真实请求。

我如何允许多个处理程序以便在调用 http.Client.Get(...) 时模拟多个响应?

最佳答案

由于原始问题使用了 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()

关于go - 使用 httptest 为多个处理程序提供服务以模拟多个请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51256080/

相关文章:

go - 为什么 goroutine 执行命令在运行之间是相同的

json - 我如何在 Go 中解析 JSON?

json - 如何在 Go 中连续追加到 JSON 文件?

json - 如何清理golang中的输入数据?

java - Spring Security 加密字符串 - Go 中解密失败

amazon-web-services - 做 dynamoattribute.UnmarshalMap 时关系总是为零

mongodb - 使用 Go 插入和查询 MongoDB 数据

go - 为什么我不能 append 到作为 golang 结构属性的 slice ?

go - 如何处理基于时间的一次性密码的 26 字节 secret ?

mysql - Golang : cannot use sql. 准备好的语句中的 NamedArg