【问题标题】:Adding POST variables to Go test http Request将 POST 变量添加到 Go 测试 http 请求
【发布时间】:2015-06-22 10:52:25
【问题描述】:

我正在尝试将表单变量添加到 Go http 请求。

这是我的 Go 测试的样子:

func sample_test(t *testing.T) {
    handler := &my_listener_class{}
    reader := strings.NewReader("number=2")
    req, _ := http.NewRequest("POST", "/my_url", reader)
    w := httptest.NewRecorder()
    handler.function_to_test(w, req)
    if w.Code != http.StatusOK {
        t.Errorf("Home page didn't return %v", http.StatusOK)
    }
}

问题是表单数据永远不会传递给我需要测试的函数。

另一个相关函数是:

func (listener *my_listener_class) function_to_test(writer http.ResponseWriter, request *http.Request) {
    ...
}

我正在使用 Go 版本 go1.3.3 darwin/amd64。

【问题讨论】:

    标签: unit-testing testing go http-post


    【解决方案1】:

    您需要在请求中添加Content-Type 标头,以便处理程序知道如何处理 POST 正文数据:

    req, _ := http.NewRequest("POST", "/my_url", reader) //BTW check for error
    req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
    

    【讨论】:

    • 我试过了,然后……咔嚓! (跑去测试)恐慌:运行时错误:无效的内存地址或nil指针取消引用[恢复]恐慌:运行时错误:无效的内存地址或nil指针取消引用[信号0xb代码=0x1 addr=0x0 pc=0x1271d0]
    • @mirage 这可能是您的处理程序中的一个问题,您没有提供足够的上下文来查看它是什么。但至少我们知道我的回答对于您的具体问题是正确的。
    • 是的,这行得通。我还有一些其他问题。现在修复了那些。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-01
    相关资源
    最近更新 更多