httptest performs two types of tests: response and server
Answer Test:
func TestHeader3D(t *testing.T) { resp := httptest.NewRecorder() uri := "/3D/header/?" path := "/home/test" unlno := "997225821" param := make(url.Values) param["param1"] = []string{path} param["param2"] = []string{unlno} req, err := http.NewRequest("GET", uri+param.Encode(), nil) if err != nil { t.Fatal(err) } http.DefaultServeMux.ServeHTTP(resp, req) if p, err := ioutil.ReadAll(resp.Body); err != nil { t.Fail() } else { if strings.Contains(string(p), "Error") { t.Errorf("header response shouldn't return error: %s", p) } else if !strings.Contains(string(p), `expected result`) { t.Errorf("header response doen't match:\n%s", p) } } }
Server test (what you need to use):
func TestIt(t *testing.T){ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") fmt.Fprintln(w, `{"fake twitter json string"}`) })) defer ts.Close() twitterUrl = ts.URL c := make(chan *twitterResult) go retrieveTweets(c) tweet := <-c if tweet != expected1 { t.Fail() } tweet = <-c if tweet != expected2 { t.Fail() } }
By the way, you do not need to pass a pointer to r, because it is already a pointer.
err = json.Unmarshal(body, r)
EDIT: for my recorder test, I could use my http handler as follows:
handler(resp, req)
But my source code does not use the default multiplex (but from Gorilla / mux), and I have a wrapper around the multiplexer, for example. insert server logging and add request context (Gorilla / context), so I had to start with the multiplexer and call ServeHTTP
nemo Apr 26 '13 at 14:36 2013-04-26 14:36
source share