Reputation: 933
I have something that looks like so:
func (client *MyCustomClient) CheckURL(url string, json_response *MyCustomResponseStruct) bool {
r, err = http.Get(url)
if err != nil {
return false
}
defer r.Body.Close()
.... do stuff with json_response
And in my test, I have the following:
func TestCheckURL(t *test.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=UTF-8")
fmt.Fprintln(w, `{"status": "success"}`)
}))
defer ts.Close()
json_response := new(MyCustomResponseStruct)
client := NewMyCustomClient() // returns instance of MyCustomClient
done := client.CheckURL("test.com", json_response)
However, it does not appear as if the HTTP test server is working and that it actually goes out to test.com, as evidenced by the log output:
Get http:/test.com: dial tcp X.Y.Z.A: i/o timeout
My question is how to properly use the httptest package to mock out this request... I read through the docs and this helpful SO Answer but I'm still stuck.
Upvotes: 2
Views: 1562
Reputation: 109377
Your client only calls the URL you provided as the first argument to the CheckURL
method. Give your client the URL of your test server:
done := client.CheckURL(ts.URL, json_response)
Upvotes: 5