加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

unit-testing – 在Golang中测试HTTP路由

发布时间:2020-12-16 19:23:38 所属栏目:大数据 来源:网络整理
导读:我正在使用Gorilla mux和net / http包创建一些路由,如下所示 package routes//some imports//some stufffunc AddQuestionRoutes(r *mux.Router) { s := r.PathPrefix("/questions").Subrouter() s.HandleFunc("/{question_id}/{question_type}",getQuestion)
我正在使用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等软件包.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读