Trying to mock http response in Go test. The code snippet below never terminates if I run it with
go test example.com/auth/...
package auth_test
import (
"testing"
"net/http/httptest"
"net/http"
)
func TestAuthorization(t *testing.T) {
t.Log("Should return 401 when Gateway returns 401")
{
url := oneOffUrlWithResponseCode(http.StatusUnauthorized)
request, _ := http.NewRequest("GET", url, nil)
response, _ := http.DefaultClient.Do(request)
if response.StatusCode != http.StatusUnauthorized {
t.Fatalf("Response should be 401 (Unauthorized)")
}
}
}
func oneOffUrlWithResponseCode(responseCode int) string {
var server *httptest.Server
server = httptest.NewServer(http.HandlerFunc(func(response http.ResponseWriter, request *http.Request) {
defer server.Close()
response.WriteHeader(responseCode)
}))
return server.URL
}
However, if I comment out this line
defer server.Close()
everything works fine.
Ideally, I do not want to "leak" *httptest.Server outside of oneOffUrlWithResponseCode function and obviously close it after first request.
Why it never terminates? What am I doing wrong? What is the right thing to do?