duanhuang7591 2018-07-10 01:28
浏览 78

使用httptest服务多个处理程序以模拟多个请求

I've googled all over for this but can't find anything.

I have a struct that takes in a http.Client and it sends several GET requests. In my tests I want to mock the responses so it's not sending real requests.

Currently I've figured out how to only serve 1 request, like this:

     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.

So once that response is mocked out and the http client is performs a new request, my tests are sending out real requests after that.

How do I allow for several handlers so I can mock several responses upon calling http.Client.Get(...)?

  • 写回答

2条回答 默认 最新

  • doulanli6146 2018-07-10 10:28
    关注

    ServeMux.Handle can be used to setup a server to handle multiple requests like in this example.

    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...
    ", addr)
        server := http.Server{Handler: mux, Addr: addr}
        log.Fatal(server.ListenAndServe())
    }
    
    func HandleHello(w http.ResponseWriter, r *http.Request) {
        log.Printf("Hello!")
    }
    

    But to be honest you probably just want to abstract the http.Client behind an interface that you've created, and then stub that with a test implementation that returns exactly what you want. By doing this you avoid the overhead of http communication in your tests.

    评论

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c