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

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

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.

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:

确定