Testing HTTP routes in Golang

前端 未结 1 1603
独厮守ぢ
独厮守ぢ 2021-02-05 22:50

I am using Gorilla mux and the net/http package to create some routes as follows

package routes

//some imports

//some stuff

func AddQuestionRoutes(r *mux.Rout         


        
1条回答
  •  后悔当初
    2021-02-05 23:25

    The use of init() here is suspect. It only executes once as part of program initialization. Instead, perhaps 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 appropriate test case. Your original code was sharing the same respRec with other tests, which probably polluted your test results.

    If you need a testing framework that provides more features like setup/teardown fixtures, see packages such as gocheck.

    0 讨论(0)
提交回复
热议问题