在Golang中测试HTTP路由 [英] Testing HTTP routes in Golang

查看:126
本文介绍了在Golang中测试HTTP路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Gorilla mux和net / http包来创建一些路线,如下所示:

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.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 返回,所以我进行了以下测试代码。

I am trying to write a test to test these routes. For example, I am trying to test the GET route specifically trying to get a 400 returned so 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)
    }
}

然而,当我运行这个测试时,我得到一个 404 可以想象,因为这个请求没有被正确路由。

However, when I run this test, I get a 404 conceivably because the request is not being routed correctly.?

当我从浏览器测试这个GET路由时,它确实返回了一个 400 ,所以我确信测试的设置方式存在问题。

When I test this GET route from the browser, it does return a 400 so I'm certain there is an issue with the way the test is setup.

推荐答案

这里使用init()是可疑的。它只作为程序初始化的一部分执行一次。相反,也许是这样的:

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

在每个适当的测试用例的开头调用setup()。您的原始代码与其他测试共享相同的respRec,这可能会污染您的测试结果。

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.

如果您需要提供更多功能的测试框架,如安装/拆卸设备,请参阅 gocheck 等软件包。

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

这篇关于在Golang中测试HTTP路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆