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

标签 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 获取?

最佳答案

您只需要在请求中设置Content-Type header 即可。

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

关于unit-testing - 创建测试请求时如何模拟简单的 POST 正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45942832/

相关文章:

javascript - 使用请求在 node.js 中传输图像与发送回调正文

php - Wordpress 是否有 $_POST、$_GET 和 $_REQUEST 的包装类?

java - 在 Java 中模拟 DTO 的最佳方法是什么?

java - 如何设置标题信息

angular - Angular 构造函数中的单元测试函数调用

performance - IIS 6.0 服务器太忙 HTTP 503 Connection_Dropped DefaultAppPool

php - 在 PHP 中使用 CURL 的 POST 给出无效的请求错误

node.js - 如何对post请求中传递的表单数据进行编码

javascript - 如何在忽略元素顺序的情况下比较 Jest 中的两个集合?

C# DispatcherHelper.CheckBeginInvokeOnUI 不会在 UnitTest 上运行