2017-08-29 102 views
1

我正在尝试为简单的表单处理程序编写单元测试。我找不到任何关于如何在我的处理程序中以r.ParseForm()接收到的方式创建表单主体的信息。我可以自己看到并从身体中读取,但在我的测试中,r.Form将始终为url.Values{},正如预期的那样。如何在创建测试请求时模拟简单的POST正文

的代码归结为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拿起?

+2

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

+0

@mkopriva唉,我能想到的是我自己。你介意加入这个答案吗?谢谢! – m90

回答

1

您只需要在请求上设置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

相关问题