我使用gotests和gorilla mux,我可以对我的http handlefunc处理程序进行单元测试,但它们没有响应正确的http请求方法,因为它们应该在gorilla mux下.我怎么能做一个“实时服务器”版本的测试?
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",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) }) } }
这里的问题是该函数响应get和post请求和
不考虑我的主路由器.这适用于单元测试功能,
但我认为最好只编写一个测试整体的综合测试
事情,一气呵成地把一切都拿走了.
使用
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)},r: newreq("POST",// 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. }) } }
虽然问题使用Gorilla mux,但本答案中的方法和细节适用于满足http.Handler接口的任何路由器.