When to use httptest.Server and httptest.ResponseRecorder
Asked Answered
N

1

6

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

Nemertean answered 18/9, 2014 at 11:50 Comment(2)
The package documentation has examples for both. Please clarify, what do you mean when you say "practical" and how these examples are not practical enough.Oxymoron
I probably shouldn't use the word 'practical', the thing is, I do not understand which to use under different condition. I shall update my question.Nemertean
O
6

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.

Oxymoron answered 18/9, 2014 at 13:6 Comment(3)
am i safe to assume that if i were to build a web app, i will not need httptest.Server at all?Nemertean
I'd say yes. You generally don't need a server to unit-test your handlers.Oxymoron
Totally clear my doubts! Thanks! In my own understanding, httptest.Server is probably used as a mock for 3rd party API, just as what you mentioned. httptest.ResponseRecorder is what I'm looking for for TDDNemertean

© 2022 - 2024 — McMap. All rights reserved.