dongyata3336 2014-08-16 05:10
浏览 32
已采纳

在Golang中测试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")
}

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

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

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.

  • 写回答

1条回答 默认 最新

  • dtvgo28624 2014-08-30 18:17
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP