英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论