【发布时间】:2016-03-02 07:58:12
【问题描述】:
我正在为在 go 中作为反向代理工作的 martini 应用程序编写测试代码,并想使用 httptest.ResponseRecorder 对其进行测试,但出现以下错误。
[martini] PANIC: interface conversion: *httptest.ResponseRecorder is not http.CloseNotifier: missing method CloseNotify
httptest.ResponseRecorder 没有方法CloseNotify()
我应该如何测试它?
package main
import (
"github.com/go-martini/martini"
"github.com/stretchr/testify/assert"
"net/http"
"net/http/httptest"
"net/http/httputil"
"net/url"
"testing"
)
func TestReverseProxy(t *testing.T) {
// Mock backend
backendResponse := "I am the backend"
backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(backendResponse))
}))
defer backend.Close()
backendURL, _ := url.Parse(backend.URL)
// Frontend
m := martini.Classic()
m.Get("/", func(w http.ResponseWriter, r *http.Request) {
proxy := httputil.NewSingleHostReverseProxy(backendURL)
proxy.ServeHTTP(w, r)
})
// Testing
req, _ := http.NewRequest("GET", "/", nil)
res := httptest.NewRecorder()
m.ServeHTTP(res, req)
assert.Equal(t, 200, res.Code, "should be equal")
}
【问题讨论】:
-
go test -test.run="^TestReverseProxy$"你的代码对我有用。您的文件是否以xxx_test.go命名?否则会失败。 -
这里可以重现
标签: go reverse-proxy martini