想用单元测试方法测一个http handler

想通过单元测试的方法测一个http接口handler 但是ResponseWriter不知道要怎么整,方法1,2,3,4都不行 1.报错 *http.ResponseWriter is pointer to interface, not interface 2.报错 **http.ResponseWriter does not implement http.ResponseWriter (missing Header method) 3.报错 invalid pointer type http.ResponseWriter for composite literal 4.会在调用AHandler中panic

package main

import (
    "fmt"
    "net/http"
    "testing"
)

func AHandler(w http.ResponseWriter, req *http.Request) {
    fmt.Println("ok!")
}

//unit test
func Test_AHandler(t *testing.T) {
    url := "http://127.0.0.1:12430/test
    req, _ := http.NewRequest("GET", url, nil)
    //1.w := new(http.ResponseWriter)
    //2.w := new(*http.ResponseWriter)
    //3.w := &http.ResponseWriter{}
    //4.var w http.ResponseWriter

    AHandler(w, req)
    fmt.Println("w:",w)
}

求高手指路~

已邀请:

keysaim

赞同来自: bingo1103 曹涛

http.ResponseWriter是一个接口,不能够实例化,要测试http,请移步官方文档

曹涛

赞同来自: bingo1103

用httptest包里面提供了两个例子。在net/http/httptest下。newrecorder函数生成一个对象.这个对象实现了responsewriter

bingo1103

赞同来自:

httptest中的例子:

package main

import (
    "fmt"
    "io"
    "io/ioutil"
    "net/http"
    "net/http/httptest"
)

func main() {
    handler := func(w http.ResponseWriter, r *http.Request) {
        io.WriteString(w, "<html><body>Hello World!</body></html>")
    }

    req := httptest.NewRequest("GET", "http://example.com/foo", nil)
    w := httptest.NewRecorder()
    handler(w, req)

    resp := w.Result()
    body, _ := ioutil.ReadAll(resp.Body)

    fmt.Println(resp.StatusCode)
    fmt.Println(resp.Header.Get("Content-Type"))
    fmt.Println(string(body))

}

要回复问题请先登录注册