golang how to live test an http server?

前端 未结 1 727
既然无缘
既然无缘 2020-12-11 04:09

I use gotests, and gorilla mux and I can unit test my http handlefunc handlers, but they do not respond to the proper http request methods as they should under the gorilla m

相关标签:
1条回答
  • 2020-12-11 04:42

    Use the net/http/httptest.Server type to test with a live server.

    func TestIndex(t *testing.T) {
      // Create server using the a router initialized elsewhere. The router
      // can be a Gorilla mux as in the question, a net/http ServeMux, 
      // http.DefaultServeMux or any value that statisfies the net/http
      // Handler interface.
      ts := httptest.NewServer(router)  
      defer ts.Close()
    
      newreq := func(method, url string, body io.Reader) *http.Request {
        r, err := http.NewRequest(method, url, body)
        if err != nil {
            t.Fatal(err)
        }
        return r
      }
    
      tests := []struct {
        name string
        r    *http.Request
      }{
        {name: "1: testing get", r: newreq("GET", ts.URL+"/", nil)},
        {name: "2: testing post", r: newreq("POST", ts.URL+"/", nil)}, // reader argument required for POST
      }
      for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            resp, err := http.DefaultClient.Do(tt.r)
            defer resp.Body.Close()
            if err != nil {
                t.Fatal(err)
            }
            // check for expected response here.
        })
      }
    }
    

    Although the question uses Gorilla mux, the approach and details in this answer apply to any router that satisfies the http.Handler interface.

    0 讨论(0)
提交回复
热议问题