<p>Hi!</p>
<p>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?</p>
<p>I created some sample code which tests the handler in file.go using the two approaches I mentioned:</p>
<p>file.go: <a href="https://play.golang.org/p/asn84yLhQC" rel="nofollow">https://play.golang.org/p/asn84yLhQC</a>
file_test.go: <a href="https://play.golang.org/p/T3ydynj33K" rel="nofollow">https://play.golang.org/p/T3ydynj33K</a></p>
<p>Thanks!</p>
<hr/>**评论:**<br/><br/>mwholt: <pre><p>Use an httptest.Server if you need to test a client. Otherwise, if you're testing your handler function, just call it directly.</p></pre>benbjohnson: <pre><p>I almost always use <em>httptest.Server</em>. It doesn't add much overhead and it lets your requests go through the full server lifecycle rather than trying to construct the <em>http.Request</em> yourself.</p></pre>dchapes: <pre><blockquote>
<p>to construct the <code>http.Request</code> yourself</p>
</blockquote>
<p>That's what <a href="https://golang.org/pkg/net/http/httptest/#NewRequest" rel="nofollow"><code>httptest.NewRequest</code></a> and <a href="https://golang.org/pkg/net/http/httptest/#ResponseRecorder" rel="nofollow"><code>httptest.ResponseRecorder</code></a> are for.
Using them is simpler than <code>httptest.Server</code> + <code>http.Client</code> for doing all the non
end-to-end HTTP testing of your handlers (which should usually be the majority of the tests).</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传