Fakes, stubs and interfaces

A test double is a value that stands in for a dependency: a fake has a working simple implementation, a stub answers with fixed data, a spy records what it was asked. Go does not need a library for any of them, because a double is just a type that satisfies the interface the code under test already uses. The interfaces lesson explained satisfaction; this one uses it as a seam.

A fake with real behaviour

The interface is the three methods the caller needs, not the twenty the production store has. memoryStore implements the whole contract in a map, so a test can exercise the logic of Rename without a database, a network or a container. A fake that implements the same behaviour as the real thing is the strongest kind of double, because the test still tests the logic rather than a script of calls.

package users import ( "errors" "testing" ) type Store interface { Get(id int) (string, error) Put(id int, name string) error } type memoryStore struct { data map[int]string } func newMemoryStore() *memoryStore { return &memoryStore{data: map[int]string{}} } func (m *memoryStore) Get(id int) (string, error) { name, ok := m.data[id] if !ok { return "", errors.New("not found") } return name, nil } func (m *memoryStore) Put(id int, name string) error { m.data[id] = name return nil } func Rename(s Store, id int, name string) error { if _, err := s.Get(id); err != nil { return err } return s.Put(id, name) } func TestRename(t *testing.T) { s := newMemoryStore() if err := s.Put(1, "ada"); err != nil { t.Fatal(err) } if err := Rename(s, 1, "grace"); err != nil { t.Fatal(err) } if got, _ := s.Get(1); got != "grace" { t.Errorf("after rename got %q, want grace", got) } } func TestRenameMissing(t *testing.T) { s := newMemoryStore() if err := Rename(s, 42, "nobody"); err == nil { t.Error("renaming a missing user returned no error") } }

go test -v .

=== RUN TestRename
--- PASS: TestRename (0.00s)
=== RUN TestRenameMissing
--- PASS: TestRenameMissing (0.00s)
PASS
ok example.com/users 0.004s

Both tests used the fake, and the missing-user case needed no setup beyond an empty map. The production code would take a Store in its constructor and pass a database-backed one, and the test passes the fake: the interface is the seam, not a testing trick.

A fake clock

Time is the dependency that makes a test flaky when it is read directly. An interface with Now() is enough to replace it, and a fake that advances on command makes the test instant and exact: no sleeps, no tolerance windows, no failure on a slow machine. Production passes realClock{}, which is one line.

package session import ( "testing" "time" ) type Clock interface { Now() time.Time } type realClock struct{} func (realClock) Now() time.Time { return time.Now() } type fakeClock struct{ t time.Time } func (f *fakeClock) Now() time.Time { return f.t } func (f *fakeClock) Advance(d time.Duration) { f.t = f.t.Add(d) } type Session struct { expires time.Time } func New(clock Clock, ttl time.Duration) *Session { return &Session{expires: clock.Now().Add(ttl)} } func (s *Session) Expired(clock Clock) bool { return clock.Now().After(s.expires) } func TestSessionExpiry(t *testing.T) { clock := &fakeClock{t: time.Date(2026, 1, 1, 12, 0, 0, 0, time.UTC)} s := New(clock, 30*time.Minute) if s.Expired(clock) { t.Fatal("a fresh session is expired") } clock.Advance(29 * time.Minute) if s.Expired(clock) { t.Error("expired before the ttl") } clock.Advance(2 * time.Minute) if !s.Expired(clock) { t.Error("still valid after the ttl") } }

go test -v .

=== RUN TestSessionExpiry
--- PASS: TestSessionExpiry (0.00s)
PASS
ok example.com/session 0.005s

The three checks ran in microseconds because nothing waited: the fake moved time forward by exactly twenty-nine and then two minutes. The only care is to pass the same clock to the constructor and to the check, which is what makes the two agree about what "now" means.

A function is a stub

When the dependency has one method, a function field is the whole double: declare a named function type with a method that calls the function, and a literal becomes the stub. The test captures the arguments in local variables and returns whatever the case needs, including an error. There is no struct, no registry and no library, and the double fits in the test that uses it.

package notify import ( "errors" "testing" ) type Notifier func(to, text string) error func (n Notifier) Send(to, text string) error { return n(to, text) } func Welcome(send Notifier, email string) error { return send(email, "welcome") } func TestWelcome(t *testing.T) { var gotTo, gotText string ok := Notifier(func(to, text string) error { gotTo, gotText = to, text return nil }) if err := Welcome(ok, "ada@example.com"); err != nil { t.Fatal(err) } if gotTo != "ada@example.com" || gotText != "welcome" { t.Errorf("sent %q %q", gotTo, gotText) } broken := Notifier(func(to, text string) error { return errors.New("smtp down") }) if err := Welcome(broken, "ada@example.com"); err == nil { t.Error("a failing notifier produced no error") } }

go test -v .

=== RUN TestWelcome
--- PASS: TestWelcome (0.00s)
PASS
ok example.com/notify 0.004s

The first stub recorded the call and the second returned an error, which covered both branches of Welcome. A function stub is the right size when the behaviour under test is one call, and the wrong size when the order of several calls matters, which is where the next lesson starts.

Exercises

  1. Add a Delete to the store interface and to both implementations, then write the test that renames and deletes in one flow. How many lines did the fake need?
  2. Make the session test fail by replacing the fake clock with realClock{} and a one-millisecond ttl. Why is that test flaky, and what does the fake remove?
  3. Turn the notifier stub into a fake that keeps the messages in a slice and can fail on the second call. Which method does the test need to check the sequence?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What is a fake in Go?

    Answer

    A simple working implementation of the interface the code uses

    A fake implements the same contract in memory and needs no library.

  2. What decides the size of the interface a test double implements?

    Answer

    What the code under test calls

    A small interface is the seam; the double implements only what is used.

  3. Why is a fake clock better than time.Sleep in a test?

    Answer

    The test is instant and exact instead of timing-dependent

    The fake moves time on command, so there is no tolerance window.

  4. What does a function type with a method give a test?

    Answer

    A one-method interface implemented by a literal

    The named function type satisfies the interface and a closure is the stub.

  5. Where does the production implementation enter the code under test?

    Answer

    Through a constructor parameter of the interface type

    The seam is the parameter; production passes the real type, tests pass a double.

  6. What should a fake do with the arguments it receives?

    Answer

    Behave with them as the real implementation would

    A fake that ignores its input tests less than a stub that records it.

  7. Which double records calls for later checking?

    Answer

    A spy

    A spy keeps the calls so the test can assert on them; the next lesson builds one.

  8. Why does the session test need the same clock in New and Expired?

    Answer

    Both must agree on what now is, or the comparison is meaningless

    The clock is the notion of now; one clock per test keeps it consistent.

  9. What is the cheapest seam for a dependency with one method?

    Answer

    An interface or a function-typed parameter

    One method needs no struct: a function type and a method is the whole double.

  10. What does a test lose when it replaces a real database with a fake?

    Answer

    The guarantees of the real engine, such as SQL, transactions and constraints

    The fake tests the logic; integration tests still have to run against the real engine.

The code on this page was run with go 1.26.10 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev