英文:
Gorilla mux returns blank url params during tests
问题
以下是翻译好的内容:
下面的代码在运行appengine服务器时提取url值,但在测试期间,url变量为空。
有任何想法为什么会这样?
func init() {
s := scheduleApi{}
r := NewAERouter()
r.HandleFunc("/leagues/{leagueId}/schedule", s.get).Methods("GET")
http.Handle("/", r.router)
}
func (s *scheduleApi) get(c appengine.Context, w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
fmt.Printf("=======================\n")
fmt.Printf("URL => %v\n", r.URL)
fmt.Printf("params => %v\n", params) // 空映射
fmt.Printf("leageid => %v\n", params["leagueId"]) // 空白
fmt.Printf("=======================\n")
}
Test
func Test_Get(t *testing.T) {
r, _ := http.NewRequest("GET", "/leagues/99/schedule", nil)
w := httptest.NewRecorder()
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
s := scheduleApi{}
c, _ := aetest.NewContext(nil)
s.get(c, w, r)
})
handler.ServeHTTP(w, r)
//...
}
英文:
The code below extracts the url value when running the appengine server, but during tests the url var are blank.
Any ideas to why this would be?
func init() {
s := scheduleApi{}
r := NewAERouter()
r.HandleFunc("/leagues/{leagueId}/schedule", s.get).Methods("GET")
http.Handle("/", r.router)
}
func (s *scheduleApi) get(c appengine.Context, w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
fmt.Printf("=======================\n")
fmt.Printf("URL => %v\n", r.URL)
fmt.Printf("params => %v\n", params) // empty map
fmt.Printf("leageid => %v\n", params["leagueId"]) // blank
fmt.Printf("=======================\n")
}
Test
func Test_Get(t *testing.T) {
r, _ := http.NewRequest("GET", "/leagues/99/schedule", nil)
w := httptest.NewRecorder()
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
s := scheduleApi{}
c, _ := aetest.NewContext(nil)
s.get(c, w, r)
})
handler.ServeHTTP(w, r)
//...
}
答案1
得分: 0
Gorilla mux需要包含在你的测试中。在你的应用代码中,你正在使用mux设置路由,但在你的测试中没有。
这里有一个处理这个问题的问题,在go-nuts上。
英文:
Gorilla mux needs to be included in your test. In your app code you are setting up the route using mux but in your test you are not.
Here is a question dealing with this issue on go-nuts.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论