Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 943
alisa Avatar asked Dec 05 '25 03:12

alisa


1 Answers

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.

like image 67
Adrian Avatar answered Dec 07 '25 18:12

Adrian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!