liveBook · Manning

Mocking

As explained in Learn Go with Pocket-Sized Projects

A mock is a test double that imitates a component's interface while allowing interactions or outputs to be controlled and inspected.

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

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Defines stubbing versus mocking, demonstrates hand-written doubles, and names generators without detailing generated-mock setup.
Examples
Uses an io.Writer test helper, an exchange-rate stub, generated mock tools, and a static service response.
What you can do after
Apply it via Go interfaces and injected test doubles to control dependency results and inspect interactions.
How it connects
Connects interfaces with dependency injection, stubbing, unit testing, and service testing.

Also explained in

Compare how 21 books explain mocking →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Go with Pocket-Sized Projects. The section links point to the parts of the book it draws on.