Seams and stubs
A test replaces behavior at a boundary. For that the boundary has to be an interface or a function, not a database call straight from the handler.
A handler that opens SQL itself is hard to check without a database. A handler that accepts a small interface is checked with an in-memory stub:
type UserStore interface {
Find(ctx context.Context, id int64) (User, error)
}
In the test you write a struct with the answer and the error you need. This is a fake or a stub. The word matters less than this: it is a controlled implementation. A mock that checks "the method was called exactly once with these arguments" easily ties the test to accidental details. Prefer checking the result: which status and which body went to the client. Interaction is checked when it is the contract, for example "exactly one audit record".
Time and randomness are holes too, if you call them directly. now func() time.Time in the server's dependencies lets you set a fixed instant. A global replacement of time.Now does not exist, and that is good: do not hide the seam in a package variable if you can pass a function.
httptest.NewRequest and httptest.NewRecorder bring up HTTP without a socket. For a handler that is enough. A real port is needed less often, for checking the server as a whole. Do not drag Docker with a database into every test if the question is about one if branch.
The interface for a test is cut to the handler's calls, not copied from every method of the driver. If the stub has grown to twenty methods, the handler knows too much. Narrow the boundary.
Practice
What to check
A handler returns a user's JSON. Which check is more durable?
- That the stub was called exactly once
- The status code and the response body
- That the word Find appears inside the handler
- The number of goroutines in the process
Where to get the time
A session lifetime is counted from "now". How do you make the test deterministic?
- Call time.Sleep until a round second
- Accept a time source from the outside and replace it in the test
- Treat time as a package global and change it from a test of another module
- Turn off the monotonic clock with a compiler flag
A thick stub
A store stub implements 20 methods, although the handler calls two. Mark the true conclusions.
- The interface is probably wider than the handler needs
- This is normal. A database driver is always like that
- It makes sense to declare, next to the handler, an interface of only the needed methods
- The problem disappears if the stub is generated