Beego端点测试-空请求URI
Beego Endpoint Testing - Empty Request URI
这是我的控制器的样子
func (o *MyController) Get() {
uri := o.Ctx.Input.URI()
beego.Trace(uri)
}
现在,如果我向相应端点发出请求,例如“http://localhost:8081/path?key=value”,我会得到 uri
的正确值
但是如果我用下面的代码测试它
func TestGet(t *testing.T) {
Convey("valid request case", t, func() {
w := httptest.NewRecorder()
uri := "/path?key=value"
r, _ := http.NewRequest("GET", uri, nil)
beego.BeeApp.Handlers.ServeHTTP(w, r)
So(w.Code, ShouldEqual, 200)
})
}
控制器中的uri为空字符串
但是,o.Ctx.Request.URL.Path 具有正确的值,即“/path”
根据文档 https://golang.org/pkg/net/http/#NewRequest
NewRequest returns a Request suitable for use with Client.Do or Transport.RoundTrip. To create a request for use with testing a Server Handler use either ReadRequest or manually update the Request fields.
对于golang 1.7,应使用以下方法创建测试请求https://golang.org/pkg/net/http/httptest/#NewRequest
NewRequest returns a new incoming server Request, suitable for passing to an http.Handler for testing.
这是我的控制器的样子
func (o *MyController) Get() {
uri := o.Ctx.Input.URI()
beego.Trace(uri)
}
现在,如果我向相应端点发出请求,例如“http://localhost:8081/path?key=value”,我会得到 uri
的正确值但是如果我用下面的代码测试它
func TestGet(t *testing.T) {
Convey("valid request case", t, func() {
w := httptest.NewRecorder()
uri := "/path?key=value"
r, _ := http.NewRequest("GET", uri, nil)
beego.BeeApp.Handlers.ServeHTTP(w, r)
So(w.Code, ShouldEqual, 200)
})
}
控制器中的uri为空字符串
但是,o.Ctx.Request.URL.Path 具有正确的值,即“/path”
根据文档 https://golang.org/pkg/net/http/#NewRequest
NewRequest returns a Request suitable for use with Client.Do or Transport.RoundTrip. To create a request for use with testing a Server Handler use either ReadRequest or manually update the Request fields.
对于golang 1.7,应使用以下方法创建测试请求https://golang.org/pkg/net/http/httptest/#NewRequest
NewRequest returns a new incoming server Request, suitable for passing to an http.Handler for testing.