Unit testing 在Golang中测试HTTP路由
我使用Gorilla mux和net/http包创建一些路由,如下所示Unit testing 在Golang中测试HTTP路由,unit-testing,go,gorilla,servemux,Unit Testing,Go,Gorilla,Servemux,我使用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")
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, 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)
}
}
在每个适当的测试用例的开头调用setup()。您的原始代码与其他测试共享相同的respRec,这可能会污染您的测试结果
如果您需要提供更多功能(如安装/拆卸夹具)的测试框架,请参阅。如果不查看
getQuestion
的代码,很难说。我重新创建了您的设置,并将getQuestion
实现为禁止操作。当我运行go test./…
时,我得到以下失败:routes\u test.go:32:服务器错误:返回了200而不是400
。解决了它。实际上,我正在运行其他测试,但我使用的是相同的respRec
,而不是使用httptest.NewRecorder()
制作一个新的记录器。我猜重用同一个httpRecorder有一些限制。你能展示AddQuestionRoutes()吗?我们能只添加测试特定的路由吗?抱歉,明白了,问题本身就有