HTTP集成测试

huangapple go评论86阅读模式
英文:

HTTP integration tests

问题

我有一个用Go编写的小型服务。我已经在使用httptest等工具进行测试,但是我在模拟数据库等内容。

我想要做的是:

  • 使用空数据库启动与生产环境中相同的服务器
  • 使用HTTP对其运行测试
  • 获取这些测试的覆盖率

空数据库部分不是问题,因为我通过环境变量使一切可配置。

对其发起请求也不是问题,因为它只是标准的Go代码...

问题是:我不知道如何以一种可以测量其覆盖率的方式启动服务器(以及其子包)。而且,主服务器代码位于main函数中...我甚至不知道是否可以从其他地方调用它(我尝试过标准方法,但没有使用反射等方式)。

我对使用Go还比较新,所以我可能在说一些无意义的话。

英文:

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

得分: 9

你可以在测试中启动http服务器,并对其进行请求。

为了更方便,你可以在测试中使用httptest.Server,并将你的主要http.Handler传递给它。httptest.Server有一些方法可以更好地控制启动和停止服务器,并提供一个URL字段来给出服务器的本地地址。

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)
英文:

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)

huangapple
  • 本文由 发表于 2015年7月29日 03:54:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/31685872.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定