doulu1945 2015-07-28 19:54
浏览 105
已采纳

Golang HTTP集成测试

I have a small service written in Go. I'm already testing it with httptest et al, but, I'm mocking the database and etc...

What I would like to do:

  • Start up the very same server I use in production with an empty database
  • Run tests against it using HTTP
  • Get the coverage of those tests

The empty database part is not a problem, since I made everything configurable via environment variables.

Make requests to it is also not the problem, as it is just standard Go code...

The problem is: I don't know how to start the server in a way that I could measure the coverage of it (and it's sub-packages). Also, the main server code is inside a main function... I don't even know if I can call it from somewhere else (I tried the standard way, but not with reflection and stuff like that).

I'm kind of new using Go, so, this I might be talking nonsense.

  • 写回答

1条回答 默认 最新

  • dongyue1988 2015-07-28 20:05
    关注

    You can start the http server in your test, and make requests against it.

    For more convenience, you can use httptest.Server in the test, and give it your primary http.Handler. The httptest.Server has some methods to better control to start and stop the server, and provides a URL field to give you the local address of the server.

    ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintln(w, "Hello, client")
    }))
    defer ts.Close()
    
    res, err := http.Get(ts.URL)
    if err != nil {
        log.Fatal(err)
    }
    greeting, err := ioutil.ReadAll(res.Body)
    res.Body.Close()
    if err != nil {
        log.Fatal(err)
    }
    
    fmt.Printf("%s", greeting)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?