moe*_*sef 2 post client json unit-testing go
我正在尝试测试我创建的用于处理 POSTing JSON 数据的路由。
我想知道如何为这条路线编写测试。
我在 a 中有 POST 数据map[string]interface{},我正在创建一个新请求,如下所示:
mcPostBody := map[string]interface{}{
"question_text": "Is this a test post for MutliQuestion?",
}
body, err = json.Marshal(mcPostBody)
req, err = http.NewRequest("POST", "/questions/", bytes.NewReader(body))
Run Code Online (Sandbox Code Playgroud)
但是,t.Log(req.PostFormValue("question_text"))记录一个空行,所以我认为我没有正确设置主体。
如何使用 JSON 数据作为 Go 中的有效负载创建 POST 请求?
因为这是请求的正文,所以您可以通过阅读req.Body来访问它,例如:
func main() {
mcPostBody := map[string]interface{}{
"question_text": "Is this a test post for MutliQuestion?",
}
body, _ := json.Marshal(mcPostBody)
req, err := http.NewRequest("POST", "/questions/", bytes.NewReader(body))
var m map[string]interface{}
err = json.NewDecoder(req.Body).Decode(&m)
req.Body.Close()
fmt.Println(err, m)
}
Run Code Online (Sandbox Code Playgroud)
//edit 根据 elithrar 的评论将代码更新为更优化的版本。