2 回答
TA贡献1891条经验 获得超3个赞
这是我的想法。你觉得怎么样?
type Env struct{
db string // should be database, just example
}
func (e *Env) httpHandler(w http.ResponseWriter, r * http.Request) {
}
// In case, create different router by different database.
func newRouter(db string) *mux.Router {
e := &Env{
db:db,
}
router := mux.NewRouter()
router.HandleFunc("/foo", e.httpHandler)
router.HandleFunc("/bar", e.httpHandler)
return router
}
func TestByDatabaseA(t *testing.T) {
r := newRouter("foo")
r.Walk(func(route *mux.Route, router *mux.Router, ancestors []*mux.Route) error {
tpl, _ := route.GetPathTemplate()
if !strings.HasPrefix(tpl,"/foo"){
return nil
}
// run test
return nil
})
}
func TestByDatabaseB(t *testing.T) {
r := newRouter("bar")
r.Walk(func(route *mux.Route, router *mux.Router, ancestors []*mux.Route) error {
tpl, _ := route.GetPathTemplate()
if !strings.HasPrefix(tpl,"/bar"){
return nil
}
// run test
return nil
})
}
TA贡献1798条经验 获得超7个赞
如果在测试套件的整个生命周期内需要单个路由器 - 并且由于您无法更改指针接收器或重新注册路由处理程序 - 则可以尝试包装以后可以更改处理程序函数的位置:HandlerFunc
type wrapperHandler struct {
Fn http.HandlerFunc
}
func (wh *wrapperHandler) HandlerFunc() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
wh.Fn.ServeHTTP(w, r) // can change `Fn` later
}
}
使用:
// setup
router := mux.NewRouter()
wh := wrapperHandler{} // fill in wh.Fn later
router.HandleFunc("/foo", wh.HandlerFunc())
e := Env{ /*db1*/ }
wh.Fn = e.httpHandler
runTest(router)
e = Env{ /*db2*/ }
wh.Fn = e.httpHandler
runTest(router)
- 2 回答
- 0 关注
- 83 浏览
添加回答
举报