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.

  • Did you ever figure out a way to get the code coverage of these httptest integration tests? – Aaron Greenlee May 15 '16 at 12:53
  • @AaronGreenlee unfortunately not. – caarlos0 May 15 '16 at 18:48
up vote 6 down vote accepted

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)
  • understood... is there a way to integrate it with my already created handlers? I believe I wasn't clear... I want to test the same code which goes to production... the routes, middlewares... everything... I'll study this httptest.Server, but, seems like it will not work with my echo (github.com/labstack/echo) code :/ Thanks, BTW! – caarlos0 Jul 28 '15 at 20:19
  • 1
    @caarlos0: the httptest.Server constructors take an http.Handler as their argument. You can plug in whatever handlers, muxers, etc you want, just like you would with the standard http.Server. – JimB Jul 28 '15 at 20:22
  • This is an unit testing example for net/http. Integration tests might be requesting without involving handlers in tests, as if they're inside of an external remote api. – Inanc Gumus Jul 3 '17 at 8:46

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.