我正在尝试为简单的表单处理程序编写单元测试。我找不到任何有关如何创建表单主体的信息,以便我的处理程序中r.ParseForm()
选择它。我可以自己查看和阅读正文,但我的测试中的r.Form
在我的应用程序中按预期工作时始终为url.Values{}
。
代码归结为the following example:
package main
import (
"fmt"
"strings"
"net/http"
"net/http/httptest"
)
func main() {
w := httptest.NewRecorder()
r := httptest.NewRequest(http.MethodPost, "/", strings.NewReader("a=1&b=2"))
handler(w, r)
}
func handler(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
fmt.Printf("form: %#v\n", r.Form)
}
打印
form: url.Values{}
当我打算打印时:
form: url.Values{"a": []string{"1"}, "b": []string{"2"}}
如何实际将正文传递给httptest.NewRequest
,以便r.ParseForm
获取正文?
答案 0 :(得分:3)
您只需在请求中设置Content-Type
标题。
package main
import (
"fmt"
"strings"
"net/http"
"net/http/httptest"
)
func main() {
w := httptest.NewRecorder()
r := httptest.NewRequest(http.MethodPost, "/", strings.NewReader("a=1&b=2"))
r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
handler(w, r)
}
func handler(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
fmt.Printf("form: %#v\n", r.Form)
}