大猩猩mux在测试期间返回空的URL参数。

huangapple go评论98阅读模式
英文:

Gorilla mux returns blank url params during tests

问题

以下是翻译好的内容:

下面的代码在运行appengine服务器时提取url值,但在测试期间,url变量为空。

有任何想法为什么会这样?

  1. func init() {
  2. s := scheduleApi{}
  3. r := NewAERouter()
  4. r.HandleFunc("/leagues/{leagueId}/schedule", s.get).Methods("GET")
  5. http.Handle("/", r.router)
  6. }
  7. func (s *scheduleApi) get(c appengine.Context, w http.ResponseWriter, r *http.Request) {
  8. params := mux.Vars(r)
  9. fmt.Printf("=======================\n")
  10. fmt.Printf("URL => %v\n", r.URL)
  11. fmt.Printf("params => %v\n", params) // 空映射
  12. fmt.Printf("leageid => %v\n", params["leagueId"]) // 空白
  13. fmt.Printf("=======================\n")
  14. }
  15. Test
  16. func Test_Get(t *testing.T) {
  17. r, _ := http.NewRequest("GET", "/leagues/99/schedule", nil)
  18. w := httptest.NewRecorder()
  19. handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  20. s := scheduleApi{}
  21. c, _ := aetest.NewContext(nil)
  22. s.get(c, w, r)
  23. })
  24. handler.ServeHTTP(w, r)
  25. //...
  26. }
英文:

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?

  1. func init() {
  2. s := scheduleApi{}
  3. r := NewAERouter()
  4. r.HandleFunc("/leagues/{leagueId}/schedule", s.get).Methods("GET")
  5. http.Handle("/", r.router)
  6. }
  7. func (s *scheduleApi) get(c appengine.Context, w http.ResponseWriter, r *http.Request) {
  8. params := mux.Vars(r)
  9. fmt.Printf("=======================\n")
  10. fmt.Printf("URL => %v\n", r.URL)
  11. fmt.Printf("params => %v\n", params) // empty map
  12. fmt.Printf("leageid => %v\n", params["leagueId"]) // blank
  13. fmt.Printf("=======================\n")
  14. }

Test

  1. func Test_Get(t *testing.T) {
  2. r, _ := http.NewRequest("GET", "/leagues/99/schedule", nil)
  3. w := httptest.NewRecorder()
  4. handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  5. s := scheduleApi{}
  6. c, _ := aetest.NewContext(nil)
  7. s.get(c, w, r)
  8. })
  9. handler.ServeHTTP(w, r)
  10. //...
  11. }

答案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.

huangapple
  • 本文由 发表于 2014年9月7日 05:19:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/25704851.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定