httptest.NewRequest vs http.NewRequest: which one to use in tests and why?

huangapple go评论80阅读模式
英文:

httptest.NewRequest vs http.NewRequest: which one to use in tests and why?

问题

Golang有两个类似的库httphttptest,它们都有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.

huangapple
  • 本文由 发表于 2017年8月15日 04:12:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/45682353.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定