Testing Go Code with Dependencies
Replace databases, email and the clock with fakes through small interfaces, and test HTTP handlers and clients with httptest.
Real code talks to databases, APIs and the clock. This section shows how to test it without those real dependencies.
Fakes and Mocks with Interfaces
Depend on small interfaces and pass in simple fakes in tests. No mocking framework needed.
type Mailer interface{ Send(to, subject string) error }
Testing HTTP with httptest
NewRecorder for handlers, NewServer for client code.
Hard-coded dependencies cannot be faked:
Code that creates its own database connection or hard-codes an API URL needs a small refactor before it can be tested.
Summary
Pass dependencies in, fake them in tests, and use httptest for anything HTTP.
Mocking in Go with Interfaces and Fakes
How to test Go code that calls databases, APIs or the clock by depending on small interfaces and writing simple fakes, without a mocking framework.
Testing HTTP Handlers and Clients with httptest
Test Go HTTP handlers with httptest.NewRecorder and NewRequest, test HTTP client code against httptest.NewServer, and check status codes, headers and JSON bodies.