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

标签 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")
    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,这可能会污染您的测试结果。

如果您需要一个提供更多功能(如设置/拆卸装置)的测试框架,请参阅 gocheck 等软件包.

关于unit-testing - 在 Golang 中测试 HTTP 路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25337126/

相关文章:

c# - Moq 验证使用返回中修改的对象,而不是实际传入的对象

java - 如何验证没有调用模拟对象的方法?莫基托

go - 通过代理重新发送时出现“Request.RequestURI 无法在客户端请求中设置”错误

go - 响应没有实现 http.Hijacker

go - 如果websocket握手超时设置为0,会发生什么情况

c# - 如何在 Visual Studio 测试中模拟数据存储库?

java - 安卓单元测试 : How to make a class more testable?

html - 需要在发起http响应后通知邮件发送状态

map - 戈朗 : traverse arbitrary map in sorted key order

Gorilla WebSocket WriteMessage 错误 - Go Lang