Golang HTTP Integration Tests

I have a little service written in Go. I am already testing it with httptest and others, but I am mocking the database, etc ....

What I would like to do:

  • Run the same server that I use when working with an empty database
  • Run tests using HTTP
  • Get coverage for these tests.

The empty part of the database is not a problem, since I made everything custom using environment variables.

Making requests to it is not a problem either, as this is just standard Go code ...

The problem is this: I do not know how to start the server in such a way that I can measure its coverage (and its subpackages). In addition, the main server code is inside the main function ... I don’t even know if I can call it from another place (I tried the standard path, but not with reflection, etc.).

I kind of use Go, so I could say stupid things.

+5
source share
1 answer

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

For your convenience, you can use httptest.Server in the test and provide it with your main http.Handler. httptest.Server has some methods that allow you to better control server start and stop and provides a URL field to give you a local server address.

 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) 
+6
source

All Articles