liveBook · Manning

Stub

As explained in 100 Go Mistakes and How to Avoid Them

A stub is a test double that supplies predetermined responses in place of a dependency.

A stub is a test double that returns predetermined values for a dependency. A common mistake is testing code that calls time.Now() directly: timing-sensitive tests can become brittle or require sleeps. section 11.6

Inject a deterministic clock

Define type now func() time.Time and store it on Cache. Production construction assigns time.Now; the test assigns func() time.Time { return parseTime(t, "2020-01-01T12:00:00.06Z") }. TrimOlderThan then evaluates identical timestamps on every run.

Choose the dependency shape according to the API:

  • Use a function type when the code needs only one operation, such as time.Now(). section 11.6
  • Group related operations such as Now and After behind an interface when the dependency grows. section 11.6
  • Avoid a mutable global clock when possible because shared state prevents isolated, parallel tests. section 11.6

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Explains function injection, interface extension, and global-state trade-offs without detailing a complete mocking framework.
Examples
Uses Cache.TrimOlderThan, injected clocks, fixed timestamps, time.Now, and a mutable global variable.
What it assumes
Assumes familiarity with Go structs and unit tests while introducing function types, dependency injection, and test doubles.
What you can do after
Apply it via dependency injection to replace time.Now with a fixed clock and run robust, isolated unit tests.
How it connects
Connects stubs to dependency injection, unit testing, function types, interfaces, test isolation, and deterministic tests.

Also explained in

Compare how 10 books explain stub →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Go Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.