Unit testing 如何使用httptest编写单元测试,处理程序在定义中使用上下文?

Unit testing 如何使用httptest编写单元测试,处理程序在定义中使用上下文?,unit-testing,go,Unit Testing,Go,一段时间以来,我一直在试图弄清楚如何编写单元来测试使用上下文作为其定义一部分的处理程序 范例 func处理程序(ctx context.context,w http.ResponseWriter,r*http.Request) 在谷歌搜索之后,我发现了这一点,这使它看起来像 //copied right from the article rr := httptest.NewRecorder() // e.g. func GetUsersHandler(ctx context.Context,

一段时间以来,我一直在试图弄清楚如何编写单元来测试使用上下文作为其定义一部分的处理程序

范例

func处理程序(ctx context.context,w http.ResponseWriter,r*http.Request)

在谷歌搜索之后,我发现了这一点,这使它看起来像

//copied right from the article

rr := httptest.NewRecorder()
// e.g. func GetUsersHandler(ctx context.Context, w http.ResponseWriter, r *http.Request)
handler := http.HandlerFunc(GetUsersHandler)
当我试图实现这样的测试时,我得到了一个错误

cannot convert Handler (type func("context".Context, http.ResponseWriter, *http.Request)) to type http.HandlerFunc
因此,我深入研究了HandleFunc的定义,发现

// The HandlerFunc type is an adapter to allow the use of
// ordinary functions as HTTP handlers. If f is a function
// with the appropriate signature, HandlerFunc(f) is a
// Handler that calls f.
type HandlerFunc func(ResponseWriter, *Request)

// ServeHTTP calls f(w, r).
func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
    f(w, r)
}
所以这个错误是有意义的。。。但现在我不知所措,因为我需要测试这个处理程序,而我似乎不能像文章建议的那样使用
httptest

是否仍然可以使用
httptest
包测试我的处理程序?如果不是,我应该如何进行测试

我用的是Go1.9

更新

//Just so its clear this is what I'm currently trying to do

data := url.Values{}
data.Set("event_type", "click")
data.Set("id", "1")
data.Set("email", "")

req, err := http.NewRequest("PUT", "/", bytes.NewBufferString(data.Encode()))
Expect(err).To(BeNil())

rr := httptest.NewRecorder()
// this is the problem line. 
// The definition of Handler isn't (w ResponseWriter, r *Request)
// So I can't create a handler to serve my mock requests
handler := http.HandlerFunc(Handler)

handler.ServeHTTP(rr, req)

httptest
包括创建伪代码所需的所有内容,出于测试目的,您只需创建适当的伪
上下文(无论在您的情况下是什么意思),然后将所有3项传递给处理程序函数,并验证它写入响应编写器的内容:

ctx := MakeMyContext()
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/myroute", nil)
// headers etc
MyHandler(ctx,w,r)
// Validate status, body, headers, whatever in r

当http.Request
已经支持上下文时,为什么要将处理程序作为另一个参数传递?这是Go1.7之前的遗留代码,整个应用程序都是以这种方式构建的。我只是在增加新的路线。尽管如此,这篇文章还是让人觉得这是一件可以做的事情,并且是作为一个例子来做的。不知道这篇文章现在有多有效。很酷,我想还是可以的,给我一点时间验证一下