dongxin8392 2017-04-19 17:31
浏览 80
已采纳

如何使用httprouter编写测试

I am writing tests for a simple REST service in GoLang. But, because I am using julienschmidt/httprouter as the routing library. I am struggling on how to write test.

main.go

package main

func main() {
   router := httprouter.New()
   bookController := controllers.NewBookController()
   router.GET("/book/:id", bookController.GetBook)
   http.ListenAndServe(":8080", router)
}

controllers

package controllers

type BookController struct {}

func NewBookController *BookController {
   return &BookController()
}

func (bc BookController) GetBook(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
   fmt.Fprintf(w,"%s", p)
}

My question is: How can test this while GetBook is neither HttpHandler nor HttpHandle

If I use a traditional handler, the test will be easy like this

func TestGetBook(t *testing.T) {
  req, _ := http.NewRequest("GET", "/book/sampleid", nil)
  rr := httptest.NewRecorder()
  handler := controllers.NewBookController().GetBook
  handler.ServeHTTP(rr,req)
  if status := rr.code; status != http.StatusOK {
    t.Errorf("Wrong status")
  }
}

The problem is, httprouter is not handler, or handlefunc. So I am stuck now

  • 写回答

4条回答 默认 最新

  • dshkmamau65777662 2017-04-19 17:55
    关注

    Just spin up a new router for each test and then register the handler under test, then pass the test request to the router, not the handler, so that the router can parse the path parameters and pass them to the handler.

    func TestGetBook(t *testing.T) {
        handler := controllers.NewBookController()
        router := httprouter.New()
        router.GET("/book/:id", handler.GetBook)
    
        req, _ := http.NewRequest("GET", "/book/sampleid", nil)
        rr := httptest.NewRecorder()
    
        router.ServeHTTP(rr, req)
        if status := rr.Code; status != http.StatusOK {
            t.Errorf("Wrong status")
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?