如何在创建测试请求时模拟简单的POST主体

时间:2017-08-29 15:20:23

标签: unit-testing http post go

我正在尝试为简单的表单处理程序编写单元测试。我找不到任何有关如何创建表单主体的信息,以便我的处理程序中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获取正文?

1 个答案:

答案 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)
}

https://play.golang.org/p/KLhNHbbNWl