doulan4939 2017-09-21 20:23
浏览 31


I've been trying for sometime to figure out how a write unit tests for handlers that use context as part of their definition.


func Handler(ctx context.Context, w http.ResponseWriter, r *http.Request)

After some googling I came accross this article which made it seem as simple as

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

When trying to to implement the tests like this I was given the error

cannot convert Handler (type func("context".Context, http.ResponseWriter, *http.Request)) to type http.HandlerFunc

So I drove into the definition of HandleFunc and found

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

So the error makes sense... but now I'm at a lose because I need to test this Handler and it doesn't seem like I can using httptest as the article suggested.

Is there anyway to test my handlers with the httptest package? If not how should I go about testing?

I'm using 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()))

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)
  • 写回答

1条回答 默认 最新

  • dsai1991 2017-09-21 20:29

    httptest includes everything you need to create a fake Request and ResponseWriter for testing purposes, you just need to create an appropriate fake Context (whatever that means in your situation) and then pass all 3 to your handler function and validate what it writes to the ResponseWriter:

    ctx := MakeMyContext()
    w := httptest.NewRecorder()
    r := httptest.NewRequest("GET", "/myroute", nil)
    // headers etc
    // Validate status, body, headers, whatever in r
    本回答被题主选为最佳回答 , 对您是否有帮助呢?



  • ¥15 韩国网站购物,KG支付的支付回调如何解决
  • ¥15 workstation导入ovf文件,报错,怎么解决呢?
  • ¥15 关于#c语言#的问题:构成555单稳态触发器,采用LED指示灯延时时间,对延时时间进行测量并显示(如楼道声控延时灯)需要Proteus仿真图和C语言代码
  • ¥15 workstation加载centos进入emergency模式,查看日志报警如图,怎样解决呢?
  • ¥50 如何用单纯形法寻优不能精准找不到给定的参数,并联机构误差识别,给定误差有7个?matlab
  • ¥15 workstation加载centos进入emergency模式,查看日志报警如图,没有XFS,怎样解决呢?
  • ¥15 应用商店如何检测在架应用内容是否违规?
  • ¥15 Ubuntu系统配置PX4
  • ¥50 nw.js调用activex
  • ¥15 数据库获取信息反馈出错,直接查询了ref字段并且还使用了User文档的_id而不是自己的