When I call http.ListenAndServe() in a test function the port does NOT close even after the tests have finished and the process has terminated. So the next time I run the tests I get the error "ListenAndServe: listen tcp :8080: bind: address already in use".
This does not happen when I run my program normally through main().
func TestIndex(t *testing.T) {
handle := handlers.ServeAndHandle("8080")
req, _ := http.NewRequest("GET", "", nil)
w := httptest.NewRecorder()
handle.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("Home page didn't return %v", http.StatusOK)
}
}
// this is just a wrapper function of ListenAndServe. m is of type handler
func ServeAndHandle(port string) http.Handler {
m := &mux{}
err := http.ListenAndServe(":"+port, m) // set listen port
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
return m
}
You can use NewUnstartedServer to create a instance, start it manually then defer closing it at the end of the test. Something along the lines:
...
ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Hello world")
}))
l, _ := net.Listen("tcp", URL)
ts.Listener = l
ts.Start()
defer ts.Close()
res, err := http.Get(URL)
if err != nil {
log.Fatal(err)
}
...