Testing HTTP routes in the Golang

I use Gorilla trash and the net / http package to create multiple routes as follows

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

I am trying to write a test to test these routes. For example, I'm trying to check the GET route, trying to get the returned 400 so that I have the following test code.

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

However, when I run this test, I get 404 presumably because the request is being routed incorrectly.?

When I test this GET route from the browser, it returns 400 , so I'm sure that there is a problem with the test setup.

+8
unit-testing go gorilla servemux
source share
1 answer

Using init () here is suspicious. It is executed only once as part of program initialization. Instead, something like:

 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, 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) } } 

where you call setup () at the beginning of each corresponding test case. Your source code used the same respRec with other tests that might have polluted the test results.

If you need a testing framework that provides more features like tuning / unloading tools, see packages like gocheck .

+7
source

All Articles