Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use httptest.Server and httptest.ResponseRecorder

As title, when to use httptest.Server and httptest.ResponseRecorder?

It seems to me that I can also test my handlers to return correct response using httptest.Server. I can simply start a httptest.Server given with my implementation of handlers, then do validations on the response's body.

Please correct if I'm wrong, I am learning Go + TDD

like image 453
Yaobin Then Avatar asked Sep 18 '14 11:09

Yaobin Then


People also ask

What is httptest NewRecorder?

httptest. NewRequest provides a convenience wrapper around http. NewRequest so you don't have to check the error making a Request object. Below that httptest. NewRecorder makes a recorder that the HTTP handler writes to as its http.

What is Httptest?

As mentioned earlier, httptest, or net/http/httptest in full, is a standard library for writing constructive and unit tests for your handlers. It provides ways to mock requests to your HTTP handlers and eliminates the need of having to run the server.

What is response Writer Golang?

type ResponseWriter interface { Header() Header Write([]byte) (int, error) WriteHeader(statusCode int) } The Golang net/http Handler interface has serveHTTP method that takes the Response Writer interface as input and this allows the Golang HTTP Server to construct HTTP Response.


1 Answers

When you just want to check, if your http.Handler does what it should, you don't need to use httptest.Server. Just call your handler with an httptest.ResponseRecorder instance and check the output as in the example.

The possible uses of httptest.Server are numerous, so here are just a couple that come to my mind:

  • If your code depends on some external services and APIs, you can use a test server to emulate them. (Although I personally would isolate all code dealing with external data sources and then use them through interfaces, so that I could easily create fake objects for my tests.)

  • If you work on a client-server application, you can use a test server to emulate the server-side when testing the client-side.

like image 181
Ainar-G Avatar answered Oct 12 '22 07:10

Ainar-G