Mocking uses a test double that implements an interface, returns controlled results, and records whether dependencies were called the expected number of times with the correct parameters. Stubbing supplies fixed results without checking interactions. section 10.4
A practical Go mocking workflow is:
- Declare a small interface close to the code that needs it, rather than exposing a broad provider contract. section 10.8 section 6.5.5
- Inject the dependency into the function so tests can supply a stub or mock instead of constructing the real implementation. section 10.8 section 6.5.5
- Use generated tools such as mockgen, mockify, or minimock when hand-written test doubles become repetitive. section 10.4 section 10.8
Controlling an exchange-rate dependency
A currency converter accepts a private exchangeRates interface with FetchExchangeRate. Tests can provide a stubRate containing either a chosen rate or an error, then verify conversion and error handling without calling a real provider. Passing nil instead demonstrates the failure mode: a runtime nil-pointer panic. section 6.5.5
Listing 4.14 logger_test.go: Test helper implementation
// testWriter is a struct that implements io.Writer.
// We use it to validate that we can write to a specific output.
type testWriter struct {
contents string
}
// Write implements the io.Writer interface.
func (tw *testWriter) Write(p []byte) (n int, err error) { #1
tw.contents = tw.contents + string(p) #2
return len(p), nil
}
A testWriter implements io.Writer, captures written bytes in contents, and lets logger tests compare output with expected messages instead of using standard output. section 4.3.2




















