简体   繁体   English

golang如何现场测试http服务器?

[英]golang how to live test an http server?

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 mux. 我使用了getests和gorilla mux,并且可以对我的http handlefunc处理程序进行单元测试,但是它们没有像在大猩猩mux下那样响应正确的http请求方法。 How I can do a "live server" version of the test? 如何进行“实时服务器”版本的测试?

func main() {
    router := mux.NewRouter()
    router.HandleFunc("/", views.Index).Methods("GET")
}

func Index(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json; charset=UTF-8")
    w.WriteHeader(http.StatusOK)

    fmt.Fprintf(w, "INDEX\n")
}

func TestIndex(t *testing.T) {

    req, _ := http.NewRequest("GET", "/", nil)
    req1, _ := http.NewRequest("POST", "/", nil)
    rr := httptest.NewRecorder()

    handler := http.HandlerFunc(Index)

    type args struct {
        w http.ResponseWriter
        r *http.Request
    }
    tests := []struct {
        name string
        args args
    }{
        {name: "1: testing get", args: args{w: rr, r: req}},
        {name: "2: testing post", args: args{w: rr, r: req1}},
    }
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            handler.ServeHTTP(tt.args.w, tt.args.r)
            log.Println(tt.args.w)
        })
    }
}

The problem here is that the function responds to both the get and post requests and doens't take into account my main router. 这里的问题是该函数同时响应get和post请求,而没有考虑我的主路由器。 This is fine for unit testing the function, but I think it would be better to just write an integrated test that tests the whole thing and gets everything out of the way in one go. 这对于功能的单元测试很好,但是我认为最好编写一个集成测试来测试整个事情,并一劳永逸地解决所有问题。

Use the net/http/httptest.Server type to test with a live server. 使用net / http / httptest.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. 尽管该问题使用Gorilla多路复用器,但此答案中的方法和详细信息适用于满足http.Handler接口的任何路由器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM