我正在使用Gorilla mux和net / http包创建一些路由,如下所示
package routes //some imports //some stuff func AddQuestionRoutes(r *mux.Router) { s := r.PathPrefix("/questions").Subrouter() s.HandleFunc("/{question_id}/{question_type}",getQuestion).Methods("GET") s.HandleFunc("/",postQuestion).Methods("POST") s.HandleFunc("/",putQuestion).Methods("PUT") s.HandleFunc("/{question_id}",deleteQuestion).Methods("DELETE") }
我正在尝试编写测试来测试这些路线.例如,我正在尝试测试GET路由,特别是试图获得400返回,所以我有以下测试代码.
package routes //some imports var m *mux.Router var req *http.Request var err error var respRec *httptest.ResponseRecorder func init() { //mux router with added question routes m = mux.NewRouter() AddQuestionRoutes(m) //The response recorder used to record HTTP responses respRec = httptest.NewRecorder() } func TestGet400(t *testing.T) { //Testing get of non existent question type req,err = http.NewRequest("GET","/questions/1/SC",nil) if err != nil { t.Fatal("Creating 'GET /questions/1/SC' request Failed!") } m.ServeHTTP(respRec,req) if respRec.Code != http.StatusBadRequest { t.Fatal("Server error: Returned ",respRec.Code," instead of ",http.StatusBadRequest) } }
但是,当我运行此测试时,我可以想象得到404,因为请求没有正确路由.
当我从浏览器测试这个GET路由时,它确实返回400,所以我确定测试设置的方式存在问题.
这里使用init()是可疑的.它只作为程序初始化的一部分执行一次.相反,也许是这样的:
func setup() { //mux router with added question routes m = mux.NewRouter() AddQuestionRoutes(m) //The response recorder used to record HTTP responses respRec = httptest.NewRecorder() } func TestGet400(t *testing.T) { setup() //Testing get of non existent question type req,http.StatusBadRequest) } }
在每个适当的测试用例的开头调用setup()的地方.您的原始代码与其他测试共享相同的respRec,这可能会污染您的测试结果.
如果您需要一个提供更多功能的测试框架,例如setup / teardown fixture,请参阅gocheck等软件包.