dsj8086 2017-02-26 21:05
浏览 91
已采纳

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

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. 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
")
}

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. 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.

  • 写回答

1条回答 默认 最新

  • dongwa3808 2017-02-26 21:20
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 在不同的执行界面调用同一个页面
  • ¥20 基于51单片机的数字频率计
  • ¥50 M3T长焦相机如何标定以及正射影像拼接问题
  • ¥15 keepalived的虚拟VIP地址 ping -s 发包测试,只能通过1472字节以下的数据包(相关搜索:静态路由)
  • ¥20 关于#stm32#的问题:STM32串口发送问题,偶校验(even),发送5A 41 FB 20.烧录程序后发现串口助手读到的是5A 41 7B A0
  • ¥15 C++map释放不掉
  • ¥15 Mabatis查询数据
  • ¥15 想知道lingo目标函数中求和公式上标是变量情况如何求解
  • ¥15 关于E22-400T22S的LORA模块的通信问题
  • ¥15 求用二阶有源低通滤波将3khz方波转为正弦波的电路