想用单元测试方法测一个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 ```go 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`,请移步[官方文档](https://golang.org/pkg/net/http/httptest/)

曹涛

赞同来自: bingo1103

用httptest包里面提供了两个例子。在net/http/httptest下。newrecorder函数生成一个对象.这个对象实现了responsewriter
httptest中的例子:
```go
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, "Hello World!")
}

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))

}
```

要回复问题请先登录注册