dongqiyang3711 2017-08-29 15:20 采纳率: 100%
浏览 199
已采纳

创建测试请求时如何模拟简单的POST正文

I'm trying to write a unit test for a simple form handler. I cannot find any info on how to create the form body in a way that it is being picked up by r.ParseForm() in my handler. I can see and read from the body myself, but r.Form in my test will always be url.Values{} when it works as expected in my application.

The code boils down to 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
", r.Form)
}

that prints

form: url.Values{}

when I'd expect it to print:

form: url.Values{"a": []string{"1"}, "b": []string{"2"}}

How do I actually pass the body to httptest.NewRequest so that it gets picked up by r.ParseForm?

  • 写回答

1条回答 默认 最新

  • duanlv1366 2017-08-29 15:31
    关注

    You just need to set the Content-Type header on the request.

    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
    ", r.Form)
    }
    

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来