Testing HTTP handlers: handler or httptest.Server?

blov · 2017-05-05 02:00:02 · 594 次点击    
这是一个分享于 2017-05-05 02:00:02 的资源,其中的信息可能已经有所发展或是发生改变。

Hi!

What are your opinions about testing an HTTP handler by running its function ServeHTTP directly and testing it by using an httptest.Server? When should I use each?

I created some sample code which tests the handler in file.go using the two approaches I mentioned:

file.go: https://play.golang.org/p/asn84yLhQC file_test.go: https://play.golang.org/p/T3ydynj33K

Thanks!


评论:

mwholt:

Use an httptest.Server if you need to test a client. Otherwise, if you're testing your handler function, just call it directly.

benbjohnson:

I almost always use httptest.Server. It doesn't add much overhead and it lets your requests go through the full server lifecycle rather than trying to construct the http.Request yourself.

dchapes:

to construct the http.Request yourself

That's what httptest.NewRequest and httptest.ResponseRecorder are for. Using them is simpler than httptest.Server + http.Client for doing all the non end-to-end HTTP testing of your handlers (which should usually be the majority of the tests).


入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

594 次点击  
加入收藏 微博
0 回复
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传