英文:
httptest.NewRequest vs http.NewRequest: which one to use in tests and why?
问题
Golang有两个类似的库http和httptest,它们都有NewRequest函数。
如果http.NewRequest已经能够满足需求,为什么还需要httptest.NewRequest呢?
如果我需要在测试中创建一个multipart/multiform请求,我应该使用哪个函数?
英文:
Golang has these two similar libs http and httptest and they both have the NewRequest func.
Why do we even need the httptest.NewRequest if http.NewRequest does it all?
If I need to create a multipart/multiform request for my tests, which one do I need to use?
答案1
得分: 9
根据文档中的说明,httptest.NewRequest "返回一个新的传入服务器请求,适用于传递给用于测试的http.Handler",而http.NewRequest "返回一个适用于Client.Do或Transport.RoundTrip的请求"。因此,如果你在单元测试中直接将请求传递给处理程序,请使用httptest.NewRequest;如果你正在使用http.Client执行完整的往返操作,请使用http.NewRequest。
英文:
As indicated in the documentation, httptest.NewRequest "returns a new incoming server Request, suitable for passing to an http.Handler for testing", while http.NewRequest "returns a Request suitable for use with Client.Do or Transport.RoundTrip." So, if you're passing the request directly to the handler in a unit test, use httptest.NewRequest, and if you're executing a full round-trip using http.Client, use http.NewRequest.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论