Mocks: gomock and hand-written doubles
A mock is a double with expectations: it records what it was asked and the test asserts on the record, or the double itself fails the test when a call does not match. The previous lesson built fakes and stubs; a mock adds the checking. Go has two ways to get one: write it by hand as a struct with a slice of calls, or generate it with mockgen from the go.uber.org/mock module. The fakes lesson is the base this one builds on.
A hand-written spy
The spy implements the same one-method interface and appends every call to a slice. The test then checks the count, the order and the arguments through a helper, which is a mock's whole job. Writing it takes fifteen lines and no dependency, and the failure message is whatever the project wants it to be.
package alert
import (
"fmt"
"testing"
)
type call struct {
to string
text string
}
type spyNotifier struct {
calls []call
}
func (s *spyNotifier) Send(to, text string) error {
s.calls = append(s.calls, call{to, text})
return nil
}
func (s *spyNotifier) expectCalls(t *testing.T, want ...string) {
t.Helper()
if len(s.calls) != len(want) {
t.Fatalf("got %d calls, want %d: %v", len(s.calls), len(want), s.calls)
}
for i, addr := range want {
if s.calls[i].to != addr {
t.Errorf("call %d went to %q, want %q", i, s.calls[i].to, addr)
}
if s.calls[i].text == "" {
t.Errorf("call %d had an empty message", i)
}
}
}
func TestBroadcast(t *testing.T) {
s := &spyNotifier{}
n, err := Broadcast(s, []string{"a@example.com", "b@example.com"}, "maintenance")
if err != nil {
t.Fatal(err)
}
if n != 2 {
t.Errorf("sent = %d, want 2", n)
}
s.expectCalls(t, "a@example.com", "b@example.com")
}
func TestBroadcastOrder(t *testing.T) {
s := &spyNotifier{}
_, _ = Broadcast(s, []string{"b@example.com", "a@example.com"}, "hi")
s.expectCalls(t, "b@example.com", "a@example.com")
}
func (s spyNotifier) String() string { return fmt.Sprintf("%d calls", len(s.calls)) }
go test -v .
=== RUN TestBroadcast
--- PASS: TestBroadcast (0.00s)
=== RUN TestBroadcastOrder
--- PASS: TestBroadcastOrder (0.00s)
PASS
ok example.com/alert 0.004s
The first test checked that two messages went to the right addresses, and the second passed the addresses in the other order and checked the record again: the spy saw the new order because it stores calls in sequence. That is the claim a fake cannot express, since a fake performs the behaviour while a spy testifies about it.
An expectation that fails
The value of an expectation is the message when it breaks. The next block has one correct test and one deliberately wrong expectation: the second says the notifier should be called three times when the correct behaviour is to stop at the failure, so the mock reports the difference and the reason.
package alert
import (
"errors"
"testing"
)
type failingNotifier struct {
failAt int
calls int
}
func (f *failingNotifier) Send(to, text string) error {
f.calls++
if f.calls == f.failAt {
return errors.New("smtp timeout")
}
return nil
}
func TestBroadcastStopsAtFailure(t *testing.T) {
f := &failingNotifier{failAt: 2}
n, err := Broadcast(f, []string{"a", "b", "c"}, "hi")
if err == nil {
t.Fatal("expected an error")
}
if n != 1 {
t.Errorf("sent = %d, want 1", n)
}
if f.calls != 2 {
t.Errorf("the notifier was called %d times, want 2: it must stop after the failure", f.calls)
}
}
func TestBroadcastStopsAtFailure_wrong(t *testing.T) {
f := &failingNotifier{failAt: 2}
_, _ = Broadcast(f, []string{"a", "b", "c"}, "hi")
if f.calls != 3 {
t.Errorf("the notifier was called %d times, want 3: this expectation is wrong", f.calls)
}
}
go test -v .
=== RUN TestBroadcastStopsAtFailure
--- PASS: TestBroadcastStopsAtFailure (0.00s)
=== RUN TestBroadcastStopsAtFailure_wrong
expect_test.go:39: the notifier was called 2 times, want 3: this expectation is wrong
--- FAIL: TestBroadcastStopsAtFailure_wrong (0.00s)
FAIL
FAIL example.com/alert 0.014s
FAIL
The first test passed and the second failed with the call count and the sentence that explains the contract. A mock library produces a similar message from an expectation like EXPECT().Send(gomock.Any(), "hi").Times(3), but the sentence has to be written the same way: an expectation is a claim about behaviour, and a wrong claim is the test's bug.
What mockgen generates
Running mockgen -source=alert.go -destination=mock_alert_test.go -package=alert writes a type with one method per interface method, a *gomock.Controller field, and calls that match against the expectations set in the test. The generated file is committed, regenerated when the interface changes, and never edited by hand. The controller verifies the expectations at the end of the test with ctrl.Finish, which is the part a hand-written spy does itself.
Use a generated mock when an interface has several methods, when the order and the repetition of calls are the contract, or when a team already standardises on gomock. Use a hand-written spy when one method is enough, when the fake should behave like the real thing, or when a dependency in the test binary is not worth the generation step. Both are committed code and both are read by the same reviewer, which is the real criterion.
Exercises
- Add a Times helper to the spy that fails when a method was called a different number of times, and use it in the broadcast tests.
- Change Broadcast to send in parallel with a goroutine per address and make the spy safe for concurrent use. What does the order test become?
- Generate a mock for the notifier with mockgen and rewrite one test with gomock. How many lines does the test lose, and what does the generated file add to the repository?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does a mock add to a fake or a stub?
Answer
Expectations about the calls, checked by the test
The recording and the assertion on it are what make it a mock.
-
How does a hand-written spy record a call in Go?
Answer
It appends the arguments to a slice in the method
A slice of a small struct is the usual record, and the test reads it.
-
What does t.Helper() do in a spy's helper?
Answer
It makes the failure point at the caller, not at the helper
The helper is plumbing; the line that failed is in the test.
-
What does mockgen generate?
Answer
A type that implements the interface and matches calls against expectations
The generated mock uses the gomock controller to verify expectations.
-
Where do gomock expectations live?
Answer
In the test, set up before the call and verified at the end
The test declares them and the controller checks them when Finish runs.
-
When is a hand-written spy better than a generated mock?
Answer
A single method and a small, readable expectation
Generation costs a file and a step; fifteen lines can be clearer.
-
What does an expectation like Times(3) assert?
Answer
That the method is called exactly three times
The count is part of the contract the test is claiming.
-
Why must the generated mock file be committed?
Answer
The test binary needs it and CI should not run mockgen
A generated file is a build input like any other; regeneration is a reviewed change.
-
What is the risk of checking call order in every test?
Answer
Tests break on refactors that do not change behaviour
Order expectations are a strict contract; use them where order matters.
-
What should a mock NOT be used for?
Answer
Replacing the real database in an integration test
A mock cannot prove the SQL works; that is what the real engine is for.
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