想用单元测试方法测一个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)
}
```
求高手指路~
没有找到相关结果
已邀请:
3 个回复
keysaim
赞同来自: bingo1103 、曹涛
曹涛
赞同来自: bingo1103
bingo1103
```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))
}
```