Skip to content

Mocking with Interfaces, Dependency Injection for Testability, testify ​

"Go interfaces generally belong in the package that uses values of the interface type, not the package that implements those values." — Go Code Review Comments, Interfaces (go.dev/wiki/CodeReviewComments)

Summary: Testable Go code receives its collaborators (a store, a payment gateway, the clock, an io.Reader) through its constructor as small interfaces that the consuming package declares, so a test can hand in a stub, a fake, a spy or a generated mock, while main wires the real implementations once, in a composition root. Focus: small and consumer-defined interfaces, "accept interfaces, return structs", constructor injection and functional options, the test-double vocabulary (dummy, stub, spy, fake, mock), hand-written fakes, testify (assert, require, mock), mockery, gomock (go.uber.org/mock), injecting the clock, io.Reader fakes, httptest, database fakes vs sqlmock vs a real database, interface embedding, nil interface vs typed nil, manual DI vs wire vs fx, and the anti-patterns (globals, init(), singletons, service locator). Learning goal: Design a Go package so every slow or non-deterministic dependency is a seam you can replace in a test, choose the cheapest double that proves the behaviour you care about, wire the real graph in one place, and recognise when a mock library, wire or fx is worth its cost.

This page owns testability by interface and injection. It does not re-teach its neighbours: how go test, table-driven tests, subtests, coverage and benchmarks work is in Testing & Benchmarking; what an interface is, type assertions and type switches are in Interfaces, Type Assertions, Type Switches & any; structs, constructors and embedding are in Structs, Methods, Embedding; where cmd/ and internal/ live is in Project Layout, golangci-lint, Makefile; the design principles behind all of it are in Dependency Inversion and Interface Segregation; real databases are in database/sql & pgx; the HTTP server and client are in net/http; readers and writers are in The io Package; time and timers are in time.Time, Timers & math/rand; context is in context.

Facts below were checked against saved copies of: Effective Go, the Go Code Review Comments and TestComments wiki pages, the Go FAQ, the Go 1.7 to 1.25 release notes that mention the features named, the testing, testing/iotest, testing/fstest and net/http/httptest sources on go.dev (pkg.go.dev returns 403 to scripted fetches), the READMEs and docs of testify, mockery, uber-go/mock, google/wire, uber-go/fx, go-sqlmock and testcontainers-go, Dave Cheney's functional-options talk, Ben Johnson's "Standard Package Layout", Martin Fowler's pages on test doubles, mocks and dependency injection, and the Laravel 13 container, facades, mocking, events and HTTP client docs. Snippets declare go 1.24 and were compiled, vetted and tested with -race on Go 1.27.4 (macOS). Generated files (mockgen v0.6.0, mockery v2.53.8, wire CLI v0.7.0) are real tool output.

Page map ​

If you are looking forGo to
The tables you can memorise in one minuteEverything in one minute
Why testing needs seams at allWhy it exists
Where the vocabulary and tools come fromWhere it comes from
A before/after checkout serviceGo
One-method interfaces and why bigger ones hurtSmall interfaces
Who declares the interfaceAccept interfaces, return structs
The after of "interface for mocking" gone wrongInterface pollution
Passing dependencies inDependency injection and constructors
Optional collaboratorsFunctional options
Dummy, stub, spy, fake, mockTest doubles
Writing your own doubleHand-written fakes
Where code can be cut openTest seams
time.Now in testsMocking the clock
Files and streamsio.Reader fakes
HTTP callshttptest as a fake server
SQLDatabase fakes vs sqlmock vs a real database
assert, require, mocktestify
Generated mocksmockery, gomock
Partial fakesInterface embedding
err != nil surprisesNil interface vs typed nil
Wiring in mainComposition root
Generated or runtime wiringwire, fx
What not to doGlobals and init(), Service locator
Keeping fakes honestContract tests
Exact messages and mechanicsMechanics
Fixing common problemsSolving the classic problems
What to use whenChoosing
Monolith to microservicesIn architecture
Reproduce itLab
Laravel container, Mockery, fakesFor PHP/Laravel developers

Everything in one minute ​

The five doubles. "Test double" is the generic word for anything that replaces a production object in a test. Each row is unpacked in Test doubles.

DoublePlain wordsHas logic?Records calls?Fails the test itself?Assert on
DummyFills a parameter, never usedNoNoOnly by panickingNothing: proves "not called"
StubCanned answersFixedNoNoResult of the code under test
SpyStub that remembersFixedYesNoThe recorded calls, afterwards
FakeWorking shortcut (in-memory map)RealNot neededNoState
MockPre-programmed expectationsScriptedYesYesVerified by the mock

The tools.

ToolWhat it isHow doubles are madeImport path
Hand-writtenYour own types in a _test.go fileYou write themnone
testify/assert, requireAssertion helpersn/agithub.com/stretchr/testify
testify/mockMock base type with On, Return, AssertExpectationsEmbed mock.Mock, forward to Calledgithub.com/stretchr/testify/mock
mockeryGenerator for testify/mock doublesgo generate or .mockery.yamlgithub.com/vektra/mockery
gomock / uber-go/mockExpectation-based mocks with a controllermockgen generatorgo.uber.org/mock
go-sqlmockA fake database/sql driversqlmock.New()github.com/DATA-DOG/go-sqlmock
net/http/httptestFake server, recorder, request builderstdlibnet/http/httptest
testing/iotest, testing/fstestFaulty readers, in-memory file systemstdlibtesting/iotest, testing/fstest
wireCompile-time DI code generatorwire.Build + generated wire_gen.gogithub.com/google/wire
fxRuntime DI and lifecycle frameworkfx.Provide, fx.Invokego.uber.org/fx

What to inject, and how.

DependencySeamTest replacement
DatabaseSmall repository interfaceIn-memory fake, sqlmock, or a real database
Outgoing HTTP*http.Client or a gateway interfacehttptest.NewServer or a fake RoundTripper
Incoming HTTPhttp.Handlerhttptest.NewRecorder + httptest.NewRequest
TimeClock interface or func() time.TimeFake clock advanced by hand
Files and streamsio.Reader, io.Writer, fs.FSstrings.Reader, bytes.Buffer, fstest.MapFS, iotest
Randomness, IDsfunc() string or an interfaceFixed sequence
Environmentgetenv func(string) string parameterA map lookup
Another serviceGateway interfaceStub, fake, or contract-tested fake

Names this page uses. The same ideas appear under several names in blog posts and tool docs; this table pins each to its section.

Name in the wildMeaning hereSection
accept interfaces return structsParameters are consumer-defined interfaces, results are concrete typesAccept interfaces, return structs
gomock / uber-go/mockThe go.uber.org/mock library and its mockgen generatorgomock
database fakes vs sqlmock vs real DB (testcontainers mention only)Three ways to test SQL-touching codeDatabase
globals and init() anti-patternHidden package-level dependenciesGlobals
service locator anti-patternAsking a registry for dependencies inside codeService locator

Why it exists ​

Code that creates its own database handle, calls time.Now() and http.Post directly can only be tested against the real database, the real clock and the real network. Those tests are slow, flaky (a timestamp can never be asserted exactly), cannot force the interesting failures (a declined card, a full disk, a timeout) and cannot run in parallel when they share globals. Go gives you a cheap cut-point: any value with the right methods satisfies an interface, with no implements clause, so you can decide the interface later, in the code that needs it.

Without seamsWith injected interfaces
Tests need a network, a database, wall-clock timeTests run in memory in microseconds
Failures are hard to provokeA stub returns ErrDeclined on demand
Tests share globals and cannot be parallelEvery test builds its own graph
The timestamp is "close to now"The timestamp is exactly 09:30:00
Fewer types, fewer linesOne more interface and one constructor parameter per dependency
Changing a dependency touches every callerChanging a dependency touches the composition root

An everyday picture. A kitchen with a standard power socket. The mixer asks for "a socket", not for "the wall of building 7". At home you plug it into the wall; in a workshop test you plug it into a battery pack that records how much power it drew. The socket is the interface, the plug is the constructor parameter, and the person who decides what is behind the socket is whoever assembles the kitchen, the composition root.

Three common misunderstandings, up front ​

  1. "Testing in Go means generating mocks for every interface." Most Go tests need a stub or a small fake; the Go wiki even warns against defining interfaces "for mocking". Mocks are for checking interactions that are the behaviour.
  2. "DI needs a framework." Constructor parameters and one Build function are dependency injection. wire and fx automate the wiring when the graph is large; they are not required.
  3. "More interfaces mean more testable code." An interface per struct is interface pollution: more files, more mock regeneration and no extra behaviour. One small interface per dependency the consumer actually uses is enough.

Where it comes from ​

Go had the idea from its first release: Effective Go says "Interfaces with only one or two methods are common in Go code, and are usually given a name derived from the method, such as io.Writer for something that implements Write." The Go proverb "The bigger the interface, the weaker the abstraction" (go-proverbs.github.io) is the same point as a slogan, and the Go FAQ and the Laws of Reflection blog post describe the mechanism: an interface variable holds a pair of a type and a value, and "can store any concrete (non-interface) value as long as that value implements the interface's methods".

The vocabulary is older than Go. Martin Fowler's bliki entry on Test Double credits Gerard Meszaros, who "is working on a book to capture patterns for using the various Xunit frameworks", with the terms dummy, fake, stub, spy and mock, and his article "Mocks Aren't Stubs" names the "classical" and "mockist" styles of test-driven development. The same author's January 2004 article "Inversion of Control Containers and the Dependency Injection pattern" named three injection styles, "Constructor Injection, Setter Injection, and Interface Injection", and contrasted DI with the Service Locator. Go code overwhelmingly uses the first.

The Go-specific timeline is short. net/http/httptest appeared early, testing.T.Helper came with Go 1.9, T.Cleanup with Go 1.14, T.TempDir with Go 1.15, T.Setenv with Go 1.17, for range N and the method-and-wildcard ServeMux patterns with Go 1.22, T.Context and slog.DiscardHandler with Go 1.24, and testing/synctest (a fake clock for goroutines) was an experiment in Go 1.24 and generally available in Go 1.25. Dave Cheney's "Functional options for friendly APIs" (dotGo 2014) credits Rob Pike's post "Self referential functions and design" for the idea. Ben Johnson's "Standard Package Layout" argues for domain interfaces at the root and a shared mock subpackage of hand-written mocks. The tools: golang/mock (gomock) was forked by Uber, whose README says "Google no longer maintains this project"; mockery generates doubles for testify/mock; wire and fx are the compile-time and runtime DI tools from Google and Uber.

Go ​

Before ​

A checkout that reaches for a package-level map, the default HTTP client, a URL variable and the wall clock. The test has exactly one seam, a global variable, and must patch and restore it.

go
// Package before is bad design, not broken code: the checkout reaches for
// package-level state, the default HTTP client and the wall clock directly,
// so a test has no seam to replace any of them.
package before

import (
	"fmt"
	"net/http"
	"strings"
	"time"
)

// PaymentURL is a global the production code reads on every call.
var PaymentURL = "https://payments.example.test/charge"

// Orders is a global "database". Every test shares it.
var Orders = map[string]int{}

// Receipt is what Checkout returns.
type Receipt struct {
	OrderID string
	Cents   int
	At      time.Time
}

// Checkout charges the card and records the order. It decides for itself
// which HTTP client, which URL, which store and which clock to use.
func Checkout(orderID string, cents int) (Receipt, error) {
	body := strings.NewReader(fmt.Sprintf(`{"order":%q,"cents":%d}`, orderID, cents))
	resp, err := http.Post(PaymentURL, "application/json", body)
	if err != nil {
		return Receipt{}, fmt.Errorf("charge: %w", err)
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return Receipt{}, fmt.Errorf("charge: unexpected status %d", resp.StatusCode)
	}
	Orders[orderID] = cents
	return Receipt{OrderID: orderID, Cents: cents, At: time.Now()}, nil
}
go
package before

import (
	"net/http"
	"net/http/httptest"
	"testing"
	"time"
)

// The only seam is a global variable. The test must mutate it, restore it,
// clear the shared map, and it can never run in parallel with another test
// that touches the same globals. The timestamp can only be asserted loosely.
func TestCheckoutNeedsGlobalPatching(t *testing.T) {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
	}))
	defer srv.Close()

	old := PaymentURL
	PaymentURL = srv.URL
	t.Cleanup(func() {
		PaymentURL = old
		clear(Orders)
	})

	start := time.Now()
	r, err := Checkout("o-1", 1250)
	if err != nil {
		t.Fatal(err)
	}
	if r.At.Before(start) || time.Since(r.At) > time.Minute {
		t.Fatalf("timestamp %v is not close to now", r.At)
	}
	if Orders["o-1"] != 1250 {
		t.Fatalf("order not stored: %v", Orders)
	}
}

After ​

The same use case with three small consumer-defined interfaces, constructor injection and one functional option. Production defaults are filled in by NewService; the test passes a stub, a spy and a fixed clock, runs its cases in parallel and asserts the exact timestamp.

go
// Package after shows the same checkout with constructor injection. The
// interfaces are small and defined here, in the consumer, not next to the
// implementations.
package after

import (
	"context"
	"errors"
	"fmt"
	"log/slog"
	"time"
)

// Order is the value the service stores.
type Order struct {
	ID        string
	Cents     int
	PaymentID string
	PlacedAt  time.Time
}

// ErrInvalidAmount is returned for a non-positive amount.
var ErrInvalidAmount = errors.New("amount must be positive")

// ErrDeclined is returned by a PaymentGateway when the card is refused.
var ErrDeclined = errors.New("payment declined")

// OrderStore is the one thing the service needs from persistence.
type OrderStore interface {
	Save(ctx context.Context, o Order) error
}

// PaymentGateway is the one thing the service needs from the payment provider.
type PaymentGateway interface {
	Charge(ctx context.Context, orderID string, cents int) (paymentID string, err error)
}

// Clock lets a test control "now".
type Clock interface {
	Now() time.Time
}

type systemClock struct{}

func (systemClock) Now() time.Time { return time.Now() }

// Service is the use case. All collaborators arrive through NewService.
type Service struct {
	store OrderStore
	pay   PaymentGateway
	clock Clock
	log   *slog.Logger
}

// Option configures optional collaborators (the functional options pattern).
type Option func(*Service)

// WithClock replaces the system clock.
func WithClock(c Clock) Option { return func(s *Service) { s.clock = c } }

// WithLogger replaces the default logger.
func WithLogger(l *slog.Logger) Option { return func(s *Service) { s.log = l } }

// NewService is the constructor: required dependencies are parameters,
// optional ones are options with production defaults.
func NewService(store OrderStore, pay PaymentGateway, opts ...Option) *Service {
	s := &Service{store: store, pay: pay, clock: systemClock{}, log: slog.Default()}
	for _, opt := range opts {
		opt(s)
	}
	return s
}

// Checkout charges first and stores second, so a declined card leaves no order.
func (s *Service) Checkout(ctx context.Context, id string, cents int) (Order, error) {
	if cents <= 0 {
		return Order{}, ErrInvalidAmount
	}
	paymentID, err := s.pay.Charge(ctx, id, cents)
	if err != nil {
		s.log.WarnContext(ctx, "charge failed", "order", id, "err", err)
		return Order{}, fmt.Errorf("checkout %s: %w", id, err)
	}
	o := Order{ID: id, Cents: cents, PaymentID: paymentID, PlacedAt: s.clock.Now()}
	if err := s.store.Save(ctx, o); err != nil {
		return Order{}, fmt.Errorf("checkout %s: save: %w", id, err)
	}
	return o, nil
}
go
package after

import (
	"context"
	"errors"
	"io"
	"log/slog"
	"testing"
	"time"
)

// stubGateway is a stub: it returns canned answers and records nothing.
type stubGateway struct {
	id  string
	err error
}

func (g stubGateway) Charge(context.Context, string, int) (string, error) { return g.id, g.err }

// spyStore is a spy: it records what it was asked to save.
type spyStore struct {
	saved []Order
	err   error
}

func (s *spyStore) Save(_ context.Context, o Order) error {
	if s.err != nil {
		return s.err
	}
	s.saved = append(s.saved, o)
	return nil
}

// fixedClock always answers the same instant.
type fixedClock struct{ t time.Time }

func (c fixedClock) Now() time.Time { return c.t }

func quiet() Option { return WithLogger(slog.New(slog.NewTextHandler(io.Discard, nil))) }

func TestCheckout(t *testing.T) {
	t.Parallel()
	at := time.Date(2026, 11, 28, 9, 30, 0, 0, time.UTC)
	errDisk := errors.New("disk full")

	tests := []struct {
		name      string
		cents     int
		gw        stubGateway
		storeErr  error
		wantErr   error
		wantSaved int
	}{
		{"happy path", 1250, stubGateway{id: "pay-1"}, nil, nil, 1},
		{"invalid amount", 0, stubGateway{id: "pay-1"}, nil, ErrInvalidAmount, 0},
		{"declined stores nothing", 500, stubGateway{err: ErrDeclined}, nil, ErrDeclined, 0},
		{"store failure surfaces", 500, stubGateway{id: "pay-2"}, errDisk, errDisk, 0},
	}
	for _, tc := range tests {
		t.Run(tc.name, func(t *testing.T) {
			t.Parallel()
			store := &spyStore{err: tc.storeErr}
			svc := NewService(store, tc.gw, WithClock(fixedClock{at}), quiet())

			got, err := svc.Checkout(t.Context(), "o-1", tc.cents)

			if !errors.Is(err, tc.wantErr) {
				t.Fatalf("err = %v, want %v", err, tc.wantErr)
			}
			if len(store.saved) != tc.wantSaved {
				t.Fatalf("saved %d orders, want %d", len(store.saved), tc.wantSaved)
			}
			if tc.wantErr == nil && (got.PlacedAt != at || got.PaymentID != "pay-1") {
				t.Fatalf("unexpected order %+v", got)
			}
		})
	}
}

The production gateway takes an *http.Client so a test can substitute the transport; an in-memory MemStore is a fake that is good enough for development too.

go
package after

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"net/http"
)

// HTTPGateway is the production PaymentGateway. It accepts an *http.Client so
// a test can pass a client whose Transport is a fake.
type HTTPGateway struct {
	BaseURL string
	Client  *http.Client
}

// Charge posts the charge and returns the provider's payment id.
func (g HTTPGateway) Charge(ctx context.Context, orderID string, cents int) (string, error) {
	payload, err := json.Marshal(map[string]any{"order": orderID, "cents": cents})
	if err != nil {
		return "", err
	}
	req, err := http.NewRequestWithContext(ctx, http.MethodPost, g.BaseURL+"/charge", bytes.NewReader(payload))
	if err != nil {
		return "", err
	}
	req.Header.Set("Content-Type", "application/json")
	resp, err := g.Client.Do(req)
	if err != nil {
		return "", fmt.Errorf("charge: %w", err)
	}
	defer resp.Body.Close()
	switch resp.StatusCode {
	case http.StatusOK:
		var out struct {
			ID string `json:"id"`
		}
		if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
			return "", fmt.Errorf("charge: decode: %w", err)
		}
		return out.ID, nil
	case http.StatusPaymentRequired:
		return "", ErrDeclined
	default:
		return "", fmt.Errorf("charge: unexpected status %d", resp.StatusCode)
	}
}
go
package after

import (
	"errors"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
)

// roundTripFunc turns a function into an http.RoundTripper: a fake transport
// with no socket at all.
type roundTripFunc func(*http.Request) (*http.Response, error)

func (f roundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }

func TestHTTPGatewayWithHttptestServer(t *testing.T) {
	t.Parallel()
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Path != "/charge" || r.Method != http.MethodPost {
			http.NotFound(w, r)
			return
		}
		if strings.Contains(r.Header.Get("Content-Type"), "json") {
			_, _ = w.Write([]byte(`{"id":"pay-77"}`))
			return
		}
		w.WriteHeader(http.StatusBadRequest)
	}))
	defer srv.Close()

	gw := HTTPGateway{BaseURL: srv.URL, Client: srv.Client()}
	id, err := gw.Charge(t.Context(), "o-1", 100)
	if err != nil || id != "pay-77" {
		t.Fatalf("id=%q err=%v", id, err)
	}
}

func TestHTTPGatewayWithFakeTransport(t *testing.T) {
	t.Parallel()
	status := func(code int) *http.Client {
		return &http.Client{Transport: roundTripFunc(func(*http.Request) (*http.Response, error) {
			return &http.Response{
				StatusCode: code,
				Body:       http.NoBody,
				Header:     make(http.Header),
			}, nil
		})}
	}
	boom := errors.New("connection reset")
	failing := &http.Client{Transport: roundTripFunc(func(*http.Request) (*http.Response, error) {
		return nil, boom
	})}

	tests := []struct {
		name   string
		client *http.Client
		want   error
	}{
		{"402 maps to ErrDeclined", status(http.StatusPaymentRequired), ErrDeclined},
		{"transport error is wrapped", failing, boom},
	}
	for _, tc := range tests {
		t.Run(tc.name, func(t *testing.T) {
			gw := HTTPGateway{BaseURL: "http://payments.invalid", Client: tc.client}
			if _, err := gw.Charge(t.Context(), "o-1", 100); !errors.Is(err, tc.want) {
				t.Fatalf("err = %v, want %v", err, tc.want)
			}
		})
	}
}
go
package after

import (
	"context"
	"sync"
)

// MemStore is an in-memory OrderStore. It is a real implementation that is
// good enough for development and tests, which makes it a fake.
type MemStore struct {
	mu     sync.Mutex
	orders map[string]Order
}

// NewMemStore returns an empty store.
func NewMemStore() *MemStore { return &MemStore{orders: map[string]Order{}} }

// Save stores or replaces an order.
func (m *MemStore) Save(_ context.Context, o Order) error {
	m.mu.Lock()
	defer m.mu.Unlock()
	m.orders[o.ID] = o
	return nil
}

// Get returns a stored order.
func (m *MemStore) Get(id string) (Order, bool) {
	m.mu.Lock()
	defer m.mu.Unlock()
	o, ok := m.orders[id]
	return o, ok
}

The Go angle ​

Go's implicit interface satisfaction is what makes this cheap: the payments package never imports the checkout package that defines PaymentGateway, and a test type in a _test.go file satisfies it by having one method. The cost is discipline: nothing stops you from declaring a 15-method interface next to the implementation, and the language will not warn you. The standard library models the habit: io.Reader, http.Handler, fs.FS, driver.Conn are all tiny, and its own test helpers (iotest, fstest.MapFS, httptest) are fakes you can use as they are.

The interface lives with the consumer; implementations point at itpackage checkout (consumer)type PaymentGateway interface {Charge(ctx, id, cents) (string, error) }Service.Checkouttakes PaymentGateway in NewServiceHTTPGateway (production)calls the payment APIreturned as a concrete structfakeGateway (test file)canned result, no networkor in-memory ledgerMockGateway (generated)mockery or mockgen outputexpectations + assertionsimplementations satisfy the interface implicitly: no "implements" keywordpackage payments(implementor)exports structs, not interfacesnever imports checkoutGo Code Review Comments: interfaces belong in the package that uses the values; return concrete types.

The concept catalogue ​

Interfaces and small interfaces Must-know ​

In plain words: An interface is a list of methods. Any type that has those methods fits, without saying so. The fewer methods you list, the more types fit and the easier a test double is to write.

Common misunderstanding: "A good interface describes the whole service." The proverb says the opposite: "The bigger the interface, the weaker the abstraction." An interface that mirrors a 12-method struct forces every double to implement 12 methods, 11 of which the code under test never calls.

Definition: type Mailer interface { Send(ctx context.Context, to, subject string) error } is a complete, useful interface. Effective Go notes that "Interfaces with only one or two methods are common in Go code". The Laws of Reflection post explains that an interface value holds a (value, type) pair and that a variable "can store any concrete (non-interface) value as long as that value implements the interface's methods". Combining two small interfaces by interface embedding is the way to build a bigger one when a consumer truly needs both.

1  consumer needs:   Send(ctx, to, subject) error                    -> Mailer (1 method)
2  production type:  smtpMailer wraps smtp.SendMail, also has Close, Ping ...  -> satisfies Mailer
3  test type:        spyMailer{calls []string} has Send              -> satisfies Mailer
4  compile check:    var _ Mailer = (*spyMailer)(nil)                -> optional assertion

Real scenario: a signup flow that only needs Send, a report job that only needs Get from a key-value store, an audit logger that only needs Write, a webhook sender that only needs Do(*http.Request).

Interface sizeDouble effortTypical fit
1 methodA function type or 3-line structMailer, Clock, io.Reader
2-3 methodsA small structOrderStore, Ledger
4-6 methodsStill manageable; consider splittingRepository with CRUD
10+ methodsGenerated mock or embedded partial fakeUsually a sign of a wrong boundary

Fix / how to use it: list the methods the function actually calls and nothing else. The after snippet has three interfaces with one method each; Interface Segregation is the same rule stated as a principle.

Accept interfaces, return structs; consumer-defined interfaces Must-know ​

In plain words: The package that uses a dependency writes the interface it needs. The package that provides the dependency just exports a concrete type with methods. Callers pass the concrete type where the interface is expected, and Go matches them up.

Common misunderstanding: "Every package should export an interface next to its implementation so others can mock it." The Code Review Comments say the opposite: "The implementing package should return concrete (usually pointer or struct) types: that way, new methods can be added to implementations without requiring extensive refactoring." The famous short form is "accept interfaces, return structs".

Definition: consumer-defined interface means the interface declaration lives in the package that has the function taking it as a parameter. The wiki shows the consumer package with type Thinger interface { Thing() bool } and func Foo(t Thinger) string, tested with a fakeThinger in consumer_test.go, and marks the producer-side NewThinger() Thinger as "DO NOT DO IT!!!".

package checkout (consumer)                package payments (implementor)
1  type PaymentGateway interface {...}     type Client struct{...}
2  func NewService(pay PaymentGateway)     func (c *Client) Charge(...) (string, error)
3  main: checkout.NewService(payments.NewClient(cfg))   -- the two packages never import each other
4  test: checkout.NewService(stubGateway{...})

Real scenario: a billing package declaring its own Store interface of two methods while the postgres package exports a big *DB; a CLI that declares Fetcher while the httpclient package exports *Client; a library that returns *Server so a new Shutdown method is not a breaking change.

PlacementWho imports whomAdding a method to the implementationDoubles
Consumer-defined interface (Go style)Neither imports the otherFreeWritten in the consumer's test
Producer-defined interface "for mocking"Consumer imports producerBreaking for every implementorGenerated, centrally
Both in a shared domain package (Ben Johnson)Both import domainChange in one placeShared mock subpackage

Fix / how to use it: return *Client, take PaymentGateway. Ben Johnson's layout is a legitimate alternative for applications: a root package holds domain types and service interfaces, subpackages implement them, and "we can use these connection points to inject mock implementations". Both honour the rule that the interface describes what the caller needs. See Dependency Inversion for the principle.

Interface pollution Important ​

In plain words: Interface pollution is declaring interfaces nobody needs: one per struct, defined next to the implementation, "just in case we want to mock it".

Common misunderstanding: "An interface in front of every service is clean architecture." It doubles the files, hides which methods callers really use, and makes the type system answer a question nobody asked. The wiki is explicit: "Do not define interfaces on the implementor side of an API 'for mocking'; instead, design the API so that it can be tested using the public API of the real implementation." And: "Do not define interfaces before they are used: without a realistic example of usage, it is too difficult to see whether an interface is even necessary, let alone what methods it ought to contain."

Definition: the symptom list is: an interface with exactly one implementation outside tests; a Foo interface and fooImpl struct in the same package; a constructor that returns the interface; a mock regenerated on every method change; methods added to an interface only because some caller wanted them.

1  producer: func NewValuer(n int) Valuer      returns the interface
2  later:    Thing gains Reset()               callers holding Valuer cannot call it
3  caller:   hidden.(interface{ Reset() })     forced type assertion to get it back
4  fix:      func NewThing(n int) *Thing       return the concrete type; consumers declare Valuer

Real scenario: a UserService interface with 20 methods and one implementation; a repository interface per table in a CRUD app; a Logger interface copied from a Java project; an HTTP client wrapper interface that mirrors http.Client method for method.

SmellWhy it hurtsCheaper alternative
One implementation, one interface, same packageNo substitution ever happensUse the struct; add an interface at the consumer if a test needs it
Returning the interface from New...Hides new methodsReturn the concrete type
Large interface "so the mock covers everything"Weak abstractionSeveral 1-2 method interfaces
Mocking pure functionsTests restate the implementationCall the real function

Fix / how to use it: write the code, notice a dependency that is slow or non-deterministic, and only then introduce the smallest interface at the call site. The ifacepitfalls snippet has the NewThing / NewValuer pair and a test that proves the hidden method is only reachable by assertion.

Dependency injection and constructor injection Must-know ​

In plain words: Dependency injection means a thing is handed what it needs instead of fetching or building it. Constructor injection is the simplest form: the dependencies are parameters of NewX.

Common misunderstanding: "DI is a framework with a container and annotations." In Go it is mostly function parameters. Martin Fowler's article lists "Constructor Injection, Setter Injection, and Interface Injection" as the three styles; idiomatic Go uses the first, because a struct built by its constructor is never half-initialised.

Definition: a type's required collaborators appear in its constructor signature, are stored in unexported fields, and are never reassigned. The compiler then enforces that nobody forgets one: after.NewService(store, pay) does not compile without both. Setter injection (svc.SetStore(...)) leaves a window where the object is unusable.

1  main:       store := after.NewMemStore()              leaf
2  main:       gw    := after.HTTPGateway{...}           leaf
3  main:       svc   := after.NewService(store, gw)      needs both
4  main:       h     := NewOrderHandler(svc)             needs svc
5  test:       svc   := after.NewService(spyStore, stubGateway{...})   same constructor, other values

Real scenario: a job runner that receives its queue client; an HTTP handler that receives a use case rather than a *sql.DB; a CLI command that receives io.Writer for output; a metrics middleware that receives a registry.

StyleGo exampleStrengthWeakness
Constructor injectionNewService(store, pay)Complete by constructionMany parameters in big types
Parameter injectionWelcome(ctx, dir, mailer, id)Pure functions, trivial testsLong parameter lists
Field injectionsvc.Store = ...Fine for tests of one fieldEasy to leave nil
Setter / interface injectionSetStore, InjectableRare in GoHalf-built objects
Global lookupvar DB *sql.DBNone for testsSee globals

Fix / how to use it: make required dependencies constructor parameters, optional ones functional options, and keep construction in the composition root. The doubles snippet shows the plain function form.

Functional options Important ​

In plain words: Functional options let a constructor take required dependencies as parameters and everything optional as WithSomething(...) arguments, so tests can override one default without a long parameter list.

Common misunderstanding: "Options are for configuration only." They are just as useful for swapping a collaborator: WithClock(fake) and WithLogger(discard) are how the after snippet makes the clock injectable while production code never mentions it. Dave Cheney's talk states the problem they solve: "Newcomers to your package have no idea which parameters are optional, and which are mandatory."

Definition: type Option func(*Service); NewService(store, pay, opts ...Option) builds the struct with production defaults and then applies each option in order. The talk credits Rob Pike's post "Self referential functions and design" as the origin, and notes that with no options "there is no work to do in this loop and so srv is unchanged".

1  NewService(store, pay)                         defaults: systemClock, slog.Default()
2  NewService(store, pay, WithClock(fixed))       option 1 replaces clock
3  NewService(store, pay, WithClock(fixed), quiet())   options apply left to right
4  wire / fx:  cannot inject variadic Options directly -> wrap in a provider function

Real scenario: an HTTP client wrapper with WithTimeout and WithTransport; a cache with WithClock; a worker pool with WithLogger; a repository with WithTx.

PatternOptional valuesDiscoverableAdds a field later
Long parameter listPass zero valuesNoBreaks callers
Config structZero value means defaultYesCompatible
Functional optionsOmitYes (With... names)Compatible
BuilderChain callsYesCompatible, more code

Fix / how to use it: required dependencies stay positional; use options for clock, logger, timeouts. Do not use options for something every caller must supply. wire cannot inject a variadic parameter, which is why ProvideService wraps NewService.

Test doubles: dummy, stub, spy, fake, mock Must-know ​

In plain words: A test double stands in for a real collaborator. The kinds differ in what they do: nothing (dummy), return fixed answers (stub), also remember calls (spy), behave like a simplified real thing (fake), or check the calls themselves (mock).

Common misunderstanding: "Mock" is the word for all of them. Fowler's Test Double entry defines five separate things: "Dummy objects are passed around but never actually used", "Fake objects actually have working implementations, but usually take some shortcut", "Stubs provide canned answers to calls made during the test", "Spies are stubs that also record some information based on how they were called", and "Mocks are pre-programmed with expectations which form a specification of the calls they are expected to receive."

Definition: the generic term is Test Double ("think stunt double"). In Go, none of these need a library: they are ordinary types with the interface's methods.

T (test)                      code under test                  double
1  svc := NewService(spy, stub)
2  svc.Checkout(ctx, "o-1", 1250)
3                             stub.Charge(...)  ------------>  returns ("pay-1", nil)    stub
4                             spy.Save(order)   ------------>  appends to saved          spy
5  assert len(spy.saved)==1   state of the spy  <-------------                           assertion after
6  mock variant: ctrl checks at cleanup that Charge was called exactly once with ("o-1", 1250)

Real scenario: a welcome mail that must not be sent for users without an address (dummy mailer panics if called); a retry loop that needs "fail twice, then succeed" (stub with a counter); an audit trail that must contain exactly one entry (spy); a checkout test that needs working persistence (fake store); a ledger transfer whose call order matters (mock).

DoubleGo formWhen it is the right oneFragility
DummydummyMailer{} that panicsParameter is required but irrelevantNone
Stubstruct with canned fields, or a function typeYou need an input or a forced errorLow
Spystruct with a slice of callsThe interaction is the output (an email was sent)Medium
FakeMap-backed implementationBehaviour spans several calls (save then get)Low if contract-tested
Mocktestify/mock, gomock, hand-written verifyOrder, count, arguments are the requirementHigh: breaks on refactoring

Fix / how to use it: pick the weakest double that proves the behaviour. Fowler's "Mocks Aren't Stubs" frames the two camps: classical tests use real objects where cheap and assert on state; mockist tests specify interactions. The snippet below shows all five against one function.

go
// Package doubles holds one small consumer so the test file can show the five
// kinds of test double (dummy, stub, fake, spy, mock) against the same code.
package doubles

import (
	"context"
	"fmt"
	"strings"
)

// Mailer is the consumer-defined interface: one method.
type Mailer interface {
	Send(ctx context.Context, to, subject string) error
}

// Directory resolves a user id to an email address.
type Directory interface {
	Email(ctx context.Context, userID string) (string, error)
}

// Welcome sends a welcome mail unless the user has no address.
func Welcome(ctx context.Context, dir Directory, m Mailer, userID string) error {
	addr, err := dir.Email(ctx, userID)
	if err != nil {
		return fmt.Errorf("welcome %s: %w", userID, err)
	}
	if strings.TrimSpace(addr) == "" {
		return nil // nothing to do; the mailer must not be touched
	}
	return m.Send(ctx, addr, "Welcome!")
}
go
package doubles

import (
	"context"
	"errors"
	"fmt"
	"testing"
)

// Dummy: fills a parameter, panics if used. Proves "never called".
type dummyMailer struct{}

func (dummyMailer) Send(context.Context, string, string) error { panic("Send must not be called") }

// Stub: canned answers, no memory of how it was used.
type stubDirectory map[string]string

func (d stubDirectory) Email(_ context.Context, id string) (string, error) {
	addr, ok := d[id]
	if !ok {
		return "", errors.New("unknown user")
	}
	return addr, nil
}

// Spy: a stub that also records calls so the test can assert afterwards.
type spyMailer struct{ calls []string }

func (s *spyMailer) Send(_ context.Context, to, subject string) error {
	s.calls = append(s.calls, to+"|"+subject)
	return nil
}

// Fake: a working implementation with a shortcut (a map instead of SMTP).
type fakeInbox struct{ boxes map[string][]string }

func newFakeInbox() *fakeInbox { return &fakeInbox{boxes: map[string][]string{}} }

func (f *fakeInbox) Send(_ context.Context, to, subject string) error {
	f.boxes[to] = append(f.boxes[to], subject)
	return nil
}

// Mock: knows what it expects and fails the test itself when the script is
// not followed. This is the style testify/mock and gomock generate.
type mockMailer struct {
	t        *testing.T
	wantTo   string
	received int
}

func (m *mockMailer) Send(_ context.Context, to, subject string) error {
	m.received++
	if to != m.wantTo {
		m.t.Errorf("Send to %q, want %q", to, m.wantTo)
	}
	return nil
}

func (m *mockMailer) verify() {
	m.t.Helper()
	if m.received != 1 {
		m.t.Errorf("Send called %d times, want exactly 1", m.received)
	}
}

func TestWelcomeDoubles(t *testing.T) {
	ctx := t.Context()
	dir := stubDirectory{"u1": "ada@example.test", "u2": "  "}

	t.Run("dummy: no address means the mailer is never touched", func(t *testing.T) {
		if err := Welcome(ctx, dir, dummyMailer{}, "u2"); err != nil {
			t.Fatal(err)
		}
	})
	t.Run("stub: directory error is wrapped", func(t *testing.T) {
		err := Welcome(ctx, dir, dummyMailer{}, "nobody")
		if err == nil || err.Error() != "welcome nobody: unknown user" {
			t.Fatalf("err = %v", err)
		}
	})
	t.Run("spy: recorded after the fact", func(t *testing.T) {
		spy := &spyMailer{}
		_ = Welcome(ctx, dir, spy, "u1")
		if fmt.Sprint(spy.calls) != "[ada@example.test|Welcome!]" {
			t.Fatalf("calls = %v", spy.calls)
		}
	})
	t.Run("fake: assert on state, not on calls", func(t *testing.T) {
		inbox := newFakeInbox()
		_ = Welcome(ctx, dir, inbox, "u1")
		if got := inbox.boxes["ada@example.test"]; len(got) != 1 || got[0] != "Welcome!" {
			t.Fatalf("inbox = %v", inbox.boxes)
		}
	})
	t.Run("mock: expectations declared up front", func(t *testing.T) {
		m := &mockMailer{t: t, wantTo: "ada@example.test"}
		_ = Welcome(ctx, dir, m, "u1")
		m.verify()
	})
}
Five test doubles: what each one doesDummyfills a parameternever calledpanics if usedStubcanned answersreturns fixed valuesno memory of callsSpystub + recorderrecords argumentstest asserts afterFakeworking shortcutreal logic, in memoryassert on stateMockpre-programmedexpects calls up frontfails the test itselfleast logic --------------------------------------------------------> most logic / most coupling to the call sequencePrefer when you canfakes and stubs: assertions on results and statesurvive refactors of how the code gets thereUse sparinglymocks and spies: assertions on callsbreak when the implementation changes, even if behaviour does not

Hand-written fakes Must-know ​

In plain words: Writing the double yourself is often the shortest route: a struct, a map and the interface's methods. You control exactly what it does, there is nothing to generate or update, and the failure message is your own.

Common misunderstanding: "Hand-written doubles do not scale." For 1-3 method interfaces they are shorter than the generator configuration. Ben Johnson wrote in the layout article: "I find many of the mocking tools to be overly complicated", and his mocks are structs with a function field per method plus an Invoked flag. Generators pay off for wide interfaces and for teams that want uniform expectations.

Definition: a hand-written fake implements the consumer's interface in the test file (or an xxxtest package when many packages share it), keeps state in plain fields, and exposes whatever the test wants to assert on. MemStore in the after snippet and MemStore/FileStore in the contract snippet are examples.

1  type spyStore struct{ saved []Order; err error }
2  func (s *spyStore) Save(_ context.Context, o Order) error { if s.err != nil { return s.err }; s.saved = append(s.saved, o); return nil }
3  test:  store := &spyStore{err: errDisk}      -> forced failure path
4  test:  store := &spyStore{}                   -> happy path, inspect store.saved

Real scenario: a spy that records emails; a stub whose Charge is a function field so each test sets its own behaviour; a fake clock with Advance; a failing io.Writer that errors after N bytes.

TechniqueCodeGood for
Struct with fieldsstubGateway{id: "pay-1", err: ErrDeclined}Fixed answers
Function field per methodtype fakeStore struct{ SaveFn func(...) error }Different behaviour per test
Function type implementing the interfacetype HandlerFunc func(...) styleOne-method interfaces
Embedded interfacestruct{ Store } overriding one methodWide interfaces (embedding)
Shared mock packagemock.UserServiceMany packages need the same double

Fix / how to use it: add var _ Store = (*spyStore)(nil) in the test when you want a compile-time check; keep the double in the same _test.go file until a second package needs it.

Test seams Important ​

In plain words: A seam is a place where you can change behaviour without editing the code around it. An interface parameter is a seam; so is a function field, a http.Client with a custom transport, or a package-level variable (a weak one).

Common misunderstanding: "If it is not an interface, it cannot be tested." Many seams are not interfaces: the getenv func(string) string parameter in run, the now func() time.Time field, a Transport on http.Client, an fs.FS argument, a t.TempDir() path.

Definition: list the seams by strength. Constructor-injected values are strongest: per instance, parallel-safe, compiler-checked. Package-level variables are weakest: process-wide, so tests must save, patch and restore them (the before snippet shows exactly that), and cannot run in parallel.

strong   constructor parameter / option        per instance, parallel-safe
         function parameter                    per call
         struct field set by the test          per instance
         http.Client.Transport                 per client
weak     package-level var (PaymentURL)        process-wide, restore with t.Cleanup
        build tags / linker -ldflags           per binary, rarely worth it

Real scenario: run(ctx, getenv) in cmd/server so the test passes a map; hard-coded file paths replaced by t.TempDir(); exec.Command wrapped in a Runner function field; os.Exit isolated in main.

SeamReplacementParallel-safe
Interface parameterAny doubleYes
Function parameter or fieldA closureYes
*http.ClientFake RoundTripperYes
getenv parametermap lookupYes
fs.FSfstest.MapFSYes
Package-level variableAssign and restoreNo

Fix / how to use it: move seams from the bottom of the table to the top as code matures; a package variable is acceptable as a stepping stone, never as the end state. t.Cleanup ("registers a function to be called when the test (or subtest) and all its subtests complete") is the tool for restoring one.

Mocking the clock: injecting time.Now Must-know ​

In plain words: Code that calls time.Now() directly cannot be tested for "expires after 30 seconds" without waiting 30 seconds. Pass the clock in, and the test moves time by hand.

Common misunderstanding: "Use time.Sleep in the test, it is only a second." Sleeping makes the suite slow and still flaky on a loaded CI machine; a fake clock is exact and instant. Another trap: a fake clock only controls code that asks it. A time.After or time.NewTimer inside the code is still real time.

Definition: two forms. An interface, type Clock interface { Now() time.Time }, suits types with many time questions (a TTL cache). A function field, now func() time.Time defaulting to time.Now, suits small types (a token). For goroutines with timers, Go 1.25 made testing/synctest generally available: "Within the bubble, time is virtualized: time package functions operate on a fake clock and the clock moves forward instantaneously if all goroutines in the bubble are blocked." It was first available in Go 1.24 under GOEXPERIMENT=synctest with a slightly different API; this page uses explicit injection and only mentions synctest.

1  clk := &fakeClock{now: 12:00:00}
2  c := NewTTLCache(clk, 30*time.Second); c.Set("k","v")   expires = 12:00:30
3  clk.Advance(29s)    c.Get("k") -> hit
4  clk.Advance(1s)     c.Get("k") -> miss  (now == expires: Before() is false)
5  no Sleep anywhere; the test takes microseconds and cannot flake

Real scenario: token and session expiry; rate limiters and retry back-off; cache TTLs; "created at" fields in a persisted order; scheduled jobs that run "at 02:00".

OptionControlsCostUse when
Clock interfaceEvery Now callOne interfaceSeveral methods need time
now func() time.Time fieldNow onlyOne fieldOne or two uses
WithClock optionSame, optionalOptionProduction default stays implicit
testing/synctest (Go 1.25)Timers and sleeps in goroutinesBubble rulesConcurrent code with timers
time.Sleep in testsNothingSlow, flakyAvoid

Fix / how to use it: compare with Before/After, not ==, and decide the boundary explicitly (the snippet's cache is a miss at exactly the TTL). See time.Time, Timers & math/rand.

go
// Package clockinject shows two ways to inject time: a one-method Clock
// interface and a plain function field. Neither calls time.Now directly.
package clockinject

import (
	"sync"
	"time"
)

// Clock is the interface form of an injected clock.
type Clock interface {
	Now() time.Time
}

// Real is the production clock.
type Real struct{}

// Now returns the wall clock time.
func (Real) Now() time.Time { return time.Now() }

type entry struct {
	value   string
	expires time.Time
}

// TTLCache expires entries after ttl according to the injected Clock.
type TTLCache struct {
	mu    sync.Mutex
	clock Clock
	ttl   time.Duration
	data  map[string]entry
}

// NewTTLCache builds a cache; pass Real{} in production.
func NewTTLCache(c Clock, ttl time.Duration) *TTLCache {
	return &TTLCache{clock: c, ttl: ttl, data: map[string]entry{}}
}

// Set stores a value that expires ttl from now.
func (c *TTLCache) Set(k, v string) {
	c.mu.Lock()
	defer c.mu.Unlock()
	c.data[k] = entry{value: v, expires: c.clock.Now().Add(c.ttl)}
}

// Get returns the value if it has not expired yet.
func (c *TTLCache) Get(k string) (string, bool) {
	c.mu.Lock()
	defer c.mu.Unlock()
	e, ok := c.data[k]
	if !ok || !c.clock.Now().Before(e.expires) {
		delete(c.data, k)
		return "", false
	}
	return e.value, true
}

// Token is the function-field form: the zero value is not usable, so the
// constructor sets now to time.Now, and a test overwrites it.
type Token struct {
	now     func() time.Time
	issued  time.Time
	maxAge  time.Duration
	subject string
}

// NewToken issues a token for subject. now == nil means time.Now.
func NewToken(subject string, maxAge time.Duration, now func() time.Time) *Token {
	if now == nil {
		now = time.Now
	}
	return &Token{now: now, issued: now(), maxAge: maxAge, subject: subject}
}

// Valid reports whether the token is still within maxAge.
func (t *Token) Valid() bool { return t.now().Sub(t.issued) < t.maxAge }
go
package clockinject

import (
	"testing"
	"time"
)

// fakeClock is advanced by hand, so the test needs no time.Sleep and cannot
// be flaky.
type fakeClock struct{ now time.Time }

func (f *fakeClock) Now() time.Time          { return f.now }
func (f *fakeClock) Advance(d time.Duration) { f.now = f.now.Add(d) }

func TestTTLCacheExpiry(t *testing.T) {
	clk := &fakeClock{now: time.Date(2026, 11, 28, 12, 0, 0, 0, time.UTC)}
	c := NewTTLCache(clk, 30*time.Second)
	c.Set("k", "v")

	clk.Advance(29 * time.Second)
	if v, ok := c.Get("k"); !ok || v != "v" {
		t.Fatalf("at 29s: got %q, %v; want hit", v, ok)
	}
	clk.Advance(1 * time.Second) // exactly ttl: expired
	if _, ok := c.Get("k"); ok {
		t.Fatal("at 30s: want miss")
	}
}

func TestTokenWithInjectedNowFunc(t *testing.T) {
	now := time.Date(2026, 11, 28, 12, 0, 0, 0, time.UTC)
	tok := NewToken("ada", time.Hour, func() time.Time { return now })

	if !tok.Valid() {
		t.Fatal("fresh token must be valid")
	}
	now = now.Add(time.Hour + time.Nanosecond)
	if tok.Valid() {
		t.Fatal("token older than maxAge must be invalid")
	}
}

func TestRealClockIsTimeNow(t *testing.T) {
	before := time.Now()
	got := Real{}.Now()
	if got.Before(before) || time.Since(got) > time.Minute {
		t.Fatalf("Real.Now() = %v, not close to now", got)
	}
}

io.Reader fakes Important ​

In plain words: If a function takes an io.Reader instead of a file name, a test hands it a string. If it takes an io.Writer, a test hands it a bytes.Buffer. The standard library also ships readers that misbehave on purpose.

Common misunderstanding: "Functions should open files themselves so callers do not have to." That welds the function to the disk. CountNonEmptyLines(r io.Reader) works on a file, an HTTP body, a gzip stream or a string, and needs no seam at all.

Definition: strings.NewReader and bytes.Buffer are the everyday fakes. testing/iotest holds fault injectors; its source says ErrReader "returns an io.Reader that returns 0, err from all Read calls", TimeoutReader "returns ErrTimeout on the second read", OneByteReader returns one byte per call and DataErrReader returns the final data together with the error. testing/fstest offers MapFS, "a simple in-memory file system for use in tests", for code that takes an fs.FS.

1  CountNonEmptyLines(strings.NewReader("a\n\n b\n"))        -> 2
2  CountNonEmptyLines(iotest.OneByteReader(r))                -> same result: tests the buffering assumption
3  CountNonEmptyLines(iotest.ErrReader(boom))                 -> error wraps boom
4  CountNonEmptyLines(iotest.TimeoutReader(r))                -> iotest.ErrTimeout after the first read
5  WriteReport(&failingWriter{left: 9}, ...)                  -> "write body" error path

Real scenario: a CSV importer fed from a string; a log parser tested with partial reads; an upload handler tested with a reader that fails halfway; a report exporter tested with a writer that fills up.

NeedFakePackage
Input bytesstrings.NewReader, bytes.NewReaderstrings, bytes
Output bytesbytes.Buffer, strings.Builderbytes, strings
Failing readiotest.ErrReader(err)testing/iotest
Slow or short readsiotest.OneByteReader, iotest.HalfReader, iotest.TimeoutReadertesting/iotest
In-memory directoryfstest.MapFStesting/fstest
Temp filest.TempDir()testing
Failing writeYour own failingWritertest file

Fix / how to use it: take the narrowest io interface (io.Reader, not *os.File), and run each parser against OneByteReader once. More in The io Package.

go
// Package readerfake takes io.Reader and io.Writer instead of files and
// network connections, so tests use strings.Reader, bytes.Buffer and the
// fault-injecting readers from testing/iotest.
package readerfake

import (
	"bufio"
	"fmt"
	"io"
	"strings"
)

// CountNonEmptyLines counts the lines of r that contain more than whitespace.
func CountNonEmptyLines(r io.Reader) (int, error) {
	sc := bufio.NewScanner(r)
	n := 0
	for sc.Scan() {
		if strings.TrimSpace(sc.Text()) != "" {
			n++
		}
	}
	if err := sc.Err(); err != nil {
		return n, fmt.Errorf("count lines: %w", err)
	}
	return n, nil
}

// WriteReport writes a two-line report to w and stops at the first error.
func WriteReport(w io.Writer, title string, lines int) error {
	if _, err := fmt.Fprintf(w, "# %s\n", title); err != nil {
		return fmt.Errorf("write title: %w", err)
	}
	if _, err := fmt.Fprintf(w, "lines: %d\n", lines); err != nil {
		return fmt.Errorf("write body: %w", err)
	}
	return nil
}
go
package readerfake

import (
	"bytes"
	"errors"
	"strings"
	"testing"
	"testing/iotest"
)

func TestCountNonEmptyLines(t *testing.T) {
	const in = "a\n\n  \nb\nc"

	t.Run("plain strings.Reader", func(t *testing.T) {
		n, err := CountNonEmptyLines(strings.NewReader(in))
		if err != nil || n != 3 {
			t.Fatalf("n=%d err=%v", n, err)
		}
	})
	t.Run("one byte per Read call", func(t *testing.T) {
		n, err := CountNonEmptyLines(iotest.OneByteReader(strings.NewReader(in)))
		if err != nil || n != 3 {
			t.Fatalf("n=%d err=%v", n, err)
		}
	})
	t.Run("data and EOF in the same Read", func(t *testing.T) {
		n, err := CountNonEmptyLines(iotest.DataErrReader(strings.NewReader(in)))
		if err != nil || n != 3 {
			t.Fatalf("n=%d err=%v", n, err)
		}
	})
	t.Run("a failing reader surfaces its error", func(t *testing.T) {
		boom := errors.New("disk on fire")
		_, err := CountNonEmptyLines(iotest.ErrReader(boom))
		if !errors.Is(err, boom) {
			t.Fatalf("err = %v, want %v", err, boom)
		}
	})
	t.Run("timeout on the second read", func(t *testing.T) {
		_, err := CountNonEmptyLines(iotest.TimeoutReader(strings.NewReader(strings.Repeat("x", 10000))))
		if !errors.Is(err, iotest.ErrTimeout) {
			t.Fatalf("err = %v, want iotest.ErrTimeout", err)
		}
	})
}

// failingWriter accepts n bytes and then fails: a fake io.Writer.
type failingWriter struct{ left int }

func (w *failingWriter) Write(p []byte) (int, error) {
	if len(p) > w.left {
		return 0, errors.New("short write")
	}
	w.left -= len(p)
	return len(p), nil
}

func TestWriteReport(t *testing.T) {
	var buf bytes.Buffer
	if err := WriteReport(&buf, "orders", 3); err != nil {
		t.Fatal(err)
	}
	if got, want := buf.String(), "# orders\nlines: 3\n"; got != want {
		t.Fatalf("got %q, want %q", got, want)
	}

	err := WriteReport(&failingWriter{left: 9}, "orders", 3)
	if err == nil || !strings.Contains(err.Error(), "write body") {
		t.Fatalf("err = %v, want a body write error", err)
	}
}

httptest as a fake server Must-know ​

In plain words: httptest.NewServer starts a real HTTP server on a local port with a handler you write in the test. Your client code talks to it exactly as it would to the real service, and you decide what the service answers.

Common misunderstanding: "To test an HTTP client I must mock http.Client." http.Client is a struct, not an interface; the seam is its Transport (an http.RoundTripper, one method) or the base URL. The httptest source describes Server as "an HTTP server for use in end-to-end HTTP tests".

Definition: three tools. httptest.NewServer plus the client from srv.Client() tests the full path, including JSON encoding and status codes. A hand-written roundTripFunc fake needs no socket and is the fastest. httptest.NewRecorder with httptest.NewRequest tests your own handlers without a server. The NewServer doc says the caller should call Close when finished; the snippets use defer srv.Close() or t.Cleanup.

client under test              httptest server (loopback, system-chosen port)
1  Charge(ctx, "o-1", 100)
2  POST /charge  ---------------> handler checks method, path, Content-Type
3  <--------------- 200 {"id":"pay-77"}
4  returns "pay-77"
fake transport variant:  Client{Transport: roundTripFunc} -> no network, return 402 or an error directly

Real scenario: a payment gateway client that must map 402 to ErrDeclined; a webhook sender that must retry on 500; a CLI that downloads a file; a service-to-service client that must send a request id header.

ToolNetworkSpeedUse for
httptest.NewServerLoopback socketFastFull client path, TLS with NewTLSServer
Fake RoundTripperNoneFastestStatus mapping, error paths, transport failures
httptest.NewRecorderNoneFastestYour handlers and middleware
Real third-party sandboxInternetSlow, flakyOccasional contract run, not unit tests

Fix / how to use it: build requests with http.NewRequestWithContext, accept an *http.Client in the constructor, and keep a fake transport for failure cases the server cannot produce (connection reset). See net/http and context.

Database fakes vs sqlmock vs a real database Must-know ​

In plain words: There are three honest ways to test code that talks to SQL: replace the repository with an in-memory fake, script a fake driver with sqlmock, or use a real database. They test different things.

Common misunderstanding: "sqlmock proves my SQL works." It proves your code sends the string you told it to expect. It never runs the query, so a typo that the database would reject passes. The go-sqlmock README describes its purpose as "to simulate any sql driver behavior in tests, without needing a real database connection".

Definition: a repository fake (a map behind the same interface) tests the callers of the repository, fast and with real behaviour. sqlmock tests the repository's own mapping code: that it scans columns, maps sql.ErrNoRows to a domain error and rolls back on failure. A real database (a local server, or a container started from the test with Testcontainers for Go, "a Go package that makes it simple to create and clean up container-based dependencies for automated integration/smoke tests") tests the SQL itself, constraints, isolation and migrations. This page names testcontainers only; running containers is out of scope here.

sql
-- the schema the sqlrepo snippet expects
CREATE TABLE users (
  id   bigint PRIMARY KEY,
  name text   NOT NULL
);

-- what NameByID sends (sqlmock matches this text as a regular expression)
SELECT name FROM users WHERE id = $1;

-- what Rename sends inside BEGIN ... COMMIT
UPDATE users SET name = $1 WHERE id = $2;
1  sqlmock.New()                                  returns *sql.DB + mock controller
2  mock.ExpectQuery(QuoteMeta(sql)).WithArgs(7).WillReturnRows(rows)
3  repo.NameByID(ctx, 7)                          scans "Ada"
4  repo.NameByID(ctx, 8)  (no rows)               -> sql.ErrNoRows -> ErrNoUser
5  mock.ExpectationsWereMet()                      fails if an expected query never ran

Real scenario: an OrderService test using a map-backed OrderStore fake; a repository test that checks Rename rolls back when UPDATE fails; a migration test against a throwaway PostgreSQL; an isolation-level bug that only a real database can show.

ApproachTestsMissesSpeedMaintenance
In-memory fake behind the interfaceCallers of the repoThe SQL, constraintsInstantKeep in sync with a contract test
sqlmockScan, error mapping, transaction flowThe SQL's validityInstantBreaks on any SQL text change
Embedded database (SQLite)Some SQLDialect differencesFastModerate
Real database / testcontainersEverythingNothing (it is the real thing)Slow, needs Docker or a serverCI setup

Fix / how to use it: put the fake under the service tests, sqlmock under repository mapping tests, and a handful of real-database tests under the SQL. See database/sql & pgx and Testing & Benchmarking.

go
// Package sqlrepo is a repository over database/sql, small enough to test with
// go-sqlmock. The consumer-facing interface is UserFinder.
package sqlrepo

import (
	"context"
	"database/sql"
	"errors"
	"fmt"
)

// ErrNoUser is returned when no row matches.
var ErrNoUser = errors.New("user not found")

// UserFinder is what callers of the repository depend on.
type UserFinder interface {
	NameByID(ctx context.Context, id int64) (string, error)
}

// Repo implements UserFinder on top of *sql.DB.
type Repo struct{ db *sql.DB }

// New wraps db.
func New(db *sql.DB) *Repo { return &Repo{db: db} }

// NameByID returns the user's name.
func (r *Repo) NameByID(ctx context.Context, id int64) (string, error) {
	var name string
	err := r.db.QueryRowContext(ctx, `SELECT name FROM users WHERE id = $1`, id).Scan(&name)
	switch {
	case errors.Is(err, sql.ErrNoRows):
		return "", ErrNoUser
	case err != nil:
		return "", fmt.Errorf("name by id %d: %w", id, err)
	}
	return name, nil
}

// Rename updates the name inside a transaction and reports whether a row changed.
func (r *Repo) Rename(ctx context.Context, id int64, name string) (bool, error) {
	tx, err := r.db.BeginTx(ctx, nil)
	if err != nil {
		return false, err
	}
	defer func() { _ = tx.Rollback() }() // no-op after Commit
	res, err := tx.ExecContext(ctx, `UPDATE users SET name = $1 WHERE id = $2`, name, id)
	if err != nil {
		return false, fmt.Errorf("rename %d: %w", id, err)
	}
	n, err := res.RowsAffected()
	if err != nil {
		return false, err
	}
	return n > 0, tx.Commit()
}
go
package sqlrepo

import (
	"errors"
	"regexp"
	"testing"

	"github.com/DATA-DOG/go-sqlmock"
)

func TestNameByID(t *testing.T) {
	db, mock, err := sqlmock.New() // default matcher: regular expressions
	if err != nil {
		t.Fatal(err)
	}
	defer db.Close()

	q := regexp.QuoteMeta(`SELECT name FROM users WHERE id = $1`)
	mock.ExpectQuery(q).WithArgs(7).WillReturnRows(sqlmock.NewRows([]string{"name"}).AddRow("Ada"))
	mock.ExpectQuery(q).WithArgs(8).WillReturnRows(sqlmock.NewRows([]string{"name"})) // no rows
	boom := errors.New("connection refused")
	mock.ExpectQuery(q).WithArgs(9).WillReturnError(boom)

	repo := New(db)
	if name, err := repo.NameByID(t.Context(), 7); err != nil || name != "Ada" {
		t.Fatalf("id 7: %q, %v", name, err)
	}
	if _, err := repo.NameByID(t.Context(), 8); !errors.Is(err, ErrNoUser) {
		t.Fatalf("id 8: err = %v, want ErrNoUser", err)
	}
	if _, err := repo.NameByID(t.Context(), 9); !errors.Is(err, boom) {
		t.Fatalf("id 9: err = %v, want the driver error", err)
	}
	if err := mock.ExpectationsWereMet(); err != nil {
		t.Fatal(err)
	}
}

func TestRenameRollsBackOnError(t *testing.T) {
	db, mock, err := sqlmock.New()
	if err != nil {
		t.Fatal(err)
	}
	defer db.Close()

	mock.ExpectBegin()
	mock.ExpectExec(regexp.QuoteMeta(`UPDATE users SET name = $1 WHERE id = $2`)).
		WithArgs("Grace", 7).
		WillReturnError(errors.New("deadlock detected"))
	mock.ExpectRollback()

	if _, err := New(db).Rename(t.Context(), 7, "Grace"); err == nil {
		t.Fatal("want error")
	}
	if err := mock.ExpectationsWereMet(); err != nil {
		t.Fatal(err)
	}
}

testify: assert, require, mock Must-know ​

In plain words: testify is the most used third-party testing module. It gives short assertion functions, a mock package for expectation-based doubles and a suite package for xUnit-style grouping.

Common misunderstanding: "Serious Go projects always use testify." The Go wiki's TestComments page says "Avoid the use of 'assert' libraries to help your tests", arguing they stop early or hide detail and "force the assert package to create a whole new sub-language". The standard library is enough and many Go teams follow it. Many others use testify for brevity. Know both positions and follow your team's.

Definition: assert.Equal(t, want, got) records a failure and continues; require.NoError(t, err) calls t.FailNow and stops the test. The README notes about suite: "The suite package does not support parallel tests." testify/mock is covered next. Testify is not part of the standard library, so the module goes in go.mod.

1  require.NoError(t, err)          stops here if err != nil (use for preconditions)
2  assert.Equal(t, 5, n)            records failure, test continues
3  assert.ErrorIs(t, err, ErrEmpty) errors.Is semantics
4  mock.AssertExpectations(t)       fails the test for any On(...) that was never called

Real scenario: a table test using assert.Equal on structs; setup that must succeed (require.NoError) before assertions; a mocked notifier verified at the end; a suite with a shared database fixture (serial only).

PackageUseCaution
assertMany checks per test, continue after failureUse require where later lines would panic
requirePreconditionsCalls FailNow: only from the test goroutine
mockExpectation doublesStrings for method names: typos found at run time
suiteSetup/teardown per suiteNo parallel tests
Standard testing + cmp.Diffcmp is github.com/google/go-cmp, not in the standard library (maintained by the Go team)More typing

Fix / how to use it: pick one style per repository. If you use testify, prefer require for errors from setup calls and assert for value checks.

testify/mock and mockery Important ​

In plain words: testify/mock gives you a base type that records calls and checks them against expectations. mockery writes the boilerplate methods for you.

Common misunderstanding: "mock.Mock knows my interface." It does not. You (or mockery) write each method to forward to Called, and the method names in On("Notify", ...) are strings, so a rename breaks tests at run time, not compile time. Mockery's EXPECT() helpers (enabled with --with-expecter) turn the method name into a real method, so a rename fails to compile, and they give typed Return(...) and RunAndReturn(...); but the expectation arguments are interface{} in the generated code, so Fetch(mock.Anything, 42) still compiles when the parameter is a string.

Definition: the testify source says "Mock is the workhorse used to track activity on another object." You embed mock.Mock, implement methods as args := m.Called(...), set expectations with On(name, args...).Return(values...), optionally .Once() or .Times(n), and call AssertExpectations(t). mock.Anything and mock.MatchedBy(func) match arguments. The mockery README: "mockery provides the ability to easily generate mocks for Golang interfaces using the stretchr/testify/mock package", and its docs add "Mockery is a project that creates mock implementations of Golang interfaces." The docs mention a v3 migration; this page's snippet pins v2.53.8 (legacy flags, go:generate), and v3 moves to a .mockery.yaml with a packages: section.

1  n := new(MockNotifier)
2  n.On("Notify", mock.Anything, "oncall", "db down").Return(nil).Once()
3  NewAlerter(n).Alert(ctx, 4, "db down")        -> calls n.Notify -> m.Called(...) -> returns nil
4  n.AssertExpectations(t)                       passes: the one expected call happened
5  forgot the call:  "FAIL: 0 out of 1 expectation(s) were met. The code you are testing needs to make 1 more call(s)."
6  mockery generated: NewMockFetcher(t) registers AssertExpectations with t.Cleanup automatically

Real scenario: an alerter that must try oncall then fall back to email; a billing client where "never charge twice" is the requirement; a fetcher interface with generated EXPECT().Fetch(...) helpers; a legacy suite of hand-rolled mock.Mock types being migrated to mockery.

FeatureHand-written mock.Mockmockery
BoilerplateYou write each methodGenerated
Typed helpersNoEXPECT() gives a typed Return and RunAndReturn; the expectation arguments are still interface{}, so a wrong argument type compiles
Cleanup assertionCall AssertExpectationsNewMockX(t) does it
Confignonego:generate flags or .mockery.yaml
Regeneration on interface changen/aRe-run the generator

Fix / how to use it: keep the interface small so the generated file stays small; commit generated files; regenerate in CI and fail on a diff. Running mockery v2.53.8 on Go 1.27.4 worked; see the mechanics section.

go
// Package testifymock shows a hand-written testify/mock double: the shape that
// mockery generates for you.
package testifymock

import (
	"context"
	"fmt"
)

// Notifier is defined by the consumer (Alerter) and has one method.
type Notifier interface {
	Notify(ctx context.Context, channel, text string) error
}

// Alerter pages the on-call channel for severe events and falls back to a
// second channel when the first one fails.
type Alerter struct {
	n Notifier
}

// NewAlerter wires the notifier.
func NewAlerter(n Notifier) *Alerter { return &Alerter{n: n} }

// Alert sends high severity events to "oncall" (falling back to "email") and
// ignores everything else.
func (a *Alerter) Alert(ctx context.Context, severity int, text string) error {
	if severity < 3 {
		return nil
	}
	if err := a.n.Notify(ctx, "oncall", text); err != nil {
		if err2 := a.n.Notify(ctx, "email", text); err2 != nil {
			return fmt.Errorf("alert: oncall: %v; email: %w", err, err2)
		}
	}
	return nil
}
go
package testifymock

import (
	"context"
	"errors"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/mock"
	"github.com/stretchr/testify/require"
)

// MockNotifier is the hand-written form of what mockery generates: embed
// mock.Mock and forward each method to Called.
type MockNotifier struct {
	mock.Mock
}

func (m *MockNotifier) Notify(ctx context.Context, channel, text string) error {
	args := m.Called(ctx, channel, text)
	return args.Error(0)
}

func TestAlertPagesOncall(t *testing.T) {
	n := new(MockNotifier)
	n.On("Notify", mock.Anything, "oncall", "db down").Return(nil).Once()

	err := NewAlerter(n).Alert(t.Context(), 4, "db down")

	require.NoError(t, err)
	n.AssertExpectations(t) // every On(...).Once() was consumed
}

func TestAlertFallsBackToEmail(t *testing.T) {
	n := new(MockNotifier)
	n.On("Notify", mock.Anything, "oncall", mock.Anything).Return(errors.New("pager offline")).Once()
	n.On("Notify", mock.Anything, "email", mock.MatchedBy(func(s string) bool { return len(s) > 0 })).Return(nil).Once()

	require.NoError(t, NewAlerter(n).Alert(t.Context(), 5, "disk full"))
	n.AssertExpectations(t)
	n.AssertNumberOfCalls(t, "Notify", 2)
}

func TestLowSeverityNeverNotifies(t *testing.T) {
	n := new(MockNotifier) // no On(...): any call would panic
	assert.NoError(t, NewAlerter(n).Alert(t.Context(), 1, "just info"))
	n.AssertNotCalled(t, "Notify", mock.Anything, mock.Anything, mock.Anything)
}
go
// Package mockerydemo uses mockery, which generates testify/mock doubles.
// Run `go generate ./...` after changing the interface.
package mockerydemo

import (
	"context"
	"errors"
)

//go:generate go run github.com/vektra/mockery/v2@v2.53.8 --name=Fetcher --inpackage --testonly --with-expecter --filename=mock_fetcher_test.go --structname=MockFetcher

// Fetcher is the consumer-defined interface.
type Fetcher interface {
	Fetch(ctx context.Context, key string) ([]byte, error)
}

// ErrEmpty is returned when the fetched payload is empty.
var ErrEmpty = errors.New("empty payload")

// Size returns the payload length for key.
func Size(ctx context.Context, f Fetcher, key string) (int, error) {
	b, err := f.Fetch(ctx, key)
	if err != nil {
		return 0, err
	}
	if len(b) == 0 {
		return 0, ErrEmpty
	}
	return len(b), nil
}
go
package mockerydemo

import (
	"errors"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/mock"
)

func TestSizeWithGeneratedMock(t *testing.T) {
	f := NewMockFetcher(t) // registers AssertExpectations with t.Cleanup
	f.EXPECT().Fetch(mock.Anything, "a").Return([]byte("hello"), nil).Once()
	f.EXPECT().Fetch(mock.Anything, "b").Return(nil, nil).Once()
	boom := errors.New("timeout")
	f.EXPECT().Fetch(mock.Anything, "c").Return(nil, boom).Once()

	n, err := Size(t.Context(), f, "a")
	assert.NoError(t, err)
	assert.Equal(t, 5, n)

	_, err = Size(t.Context(), f, "b")
	assert.ErrorIs(t, err, ErrEmpty)

	_, err = Size(t.Context(), f, "c")
	assert.ErrorIs(t, err, boom)
}

gomock and uber-go/mock Important ​

In plain words: gomock is the other big mocking library. You describe the expected calls on a controller in the test (EXPECT().Debit(...).Return(nil)), and the generated mock fails the test if the code under test deviates.

Common misunderstanding: "github.com/golang/mock is the current home." It is archived in practice: the uber-go/mock README says Google "no longer maintains this project", and the maintained fork is go.uber.org/mock, whose generator is mockgen. Import paths are go.uber.org/mock/gomock.

Definition: mockgen "has three modes of operation: archive, source and package". The snippet uses source mode: mockgen -source=ledger.go -destination=mock_ledger_test.go -package=gomockdemo. gomock.NewController(t) "registers cleanup function to automatically call Controller.Finish when the test and all its subtests complete", so missing calls are detected without defer ctrl.Finish(). gomock.InOrder(...) enforces call order; gomock.Any() is the wildcard matcher.

1  ctrl := gomock.NewController(t)
2  l := NewMockLedger(ctrl)
3  gomock.InOrder(l.EXPECT().Balance(...), l.EXPECT().Debit(...), l.EXPECT().Credit(...))
4  Transfer(ctx, l, "a", "b", 300)
5  forgot Credit expectation:  "Unexpected call to *gomockdemo.MockLedger.Credit(...) because: there are no expected calls of the method "Credit" for that receiver"
6  cleanup: any expected call that never happened fails the test

Real scenario: a ledger transfer whose debit must precede the credit; a refund path that must call Credit on the source exactly once; a repository whose Save must not be called after a declined payment.

Featuregomock / mockgentestify/mock + mockery
Expectation styleEXPECT().Method(args).Return(...)On("Method", args).Return(...)
Orderinggomock.InOrderCall.NotBefore(...) and mock.InOrder(...)
Unexpected callFails immediatelyPanics (no matching On)
Arg matchersAny, Eq, Nil, custom MatcherAnything, MatchedBy
Generatormockgen (source / package / archive)mockery
Type safetyRecorder arguments are any; return values are checked at run timeMethod names typed via EXPECT(); arguments are interface{}, Return/RunAndReturn typed

Fix / how to use it: one library per repository. The first mockgen release I tried (v0.5.2) failed to build on Go 1.27.4 because it pulls an old golang.org/x/tools; v0.6.0 worked. The runtime import and the generator version should match.

go
// Package gomockdemo uses go.uber.org/mock (gomock). The mock lives in
// mock_ledger_test.go and is produced by mockgen from this file.
package gomockdemo

import (
	"context"
	"fmt"
)

//go:generate go run go.uber.org/mock/mockgen@v0.6.0 -source=ledger.go -destination=mock_ledger_test.go -package=gomockdemo

// Ledger is the consumer-defined interface for the transfer use case.
type Ledger interface {
	Balance(ctx context.Context, account string) (int64, error)
	Debit(ctx context.Context, account string, cents int64) error
	Credit(ctx context.Context, account string, cents int64) error
}

// ErrInsufficient is returned when the source account cannot cover the amount.
var ErrInsufficient = fmt.Errorf("insufficient funds")

// Transfer moves cents between accounts: check, debit, credit.
func Transfer(ctx context.Context, l Ledger, from, to string, cents int64) error {
	bal, err := l.Balance(ctx, from)
	if err != nil {
		return err
	}
	if bal < cents {
		return ErrInsufficient
	}
	if err := l.Debit(ctx, from, cents); err != nil {
		return err
	}
	if err := l.Credit(ctx, to, cents); err != nil {
		// compensate so money is not lost
		if rerr := l.Credit(ctx, from, cents); rerr != nil {
			return fmt.Errorf("credit failed (%v) and refund failed: %w", err, rerr)
		}
		return err
	}
	return nil
}
go
package gomockdemo

import (
	"errors"
	"testing"

	"go.uber.org/mock/gomock"
)

func TestTransferHappyPathInOrder(t *testing.T) {
	ctrl := gomock.NewController(t) // since gomock 1.5 Finish is called via t.Cleanup
	l := NewMockLedger(ctrl)

	gomock.InOrder(
		l.EXPECT().Balance(gomock.Any(), "a").Return(int64(1000), nil),
		l.EXPECT().Debit(gomock.Any(), "a", int64(300)).Return(nil),
		l.EXPECT().Credit(gomock.Any(), "b", int64(300)).Return(nil),
	)

	if err := Transfer(t.Context(), l, "a", "b", 300); err != nil {
		t.Fatal(err)
	}
}

func TestTransferRefundsWhenCreditFails(t *testing.T) {
	ctrl := gomock.NewController(t)
	l := NewMockLedger(ctrl)
	boom := errors.New("ledger b unavailable")

	l.EXPECT().Balance(gomock.Any(), "a").Return(int64(1000), nil)
	l.EXPECT().Debit(gomock.Any(), "a", int64(300)).Return(nil)
	l.EXPECT().Credit(gomock.Any(), "b", int64(300)).Return(boom)
	l.EXPECT().Credit(gomock.Any(), "a", int64(300)).Return(nil).Times(1) // the refund

	if err := Transfer(t.Context(), l, "a", "b", 300); !errors.Is(err, boom) {
		t.Fatalf("err = %v, want %v", err, boom)
	}
}

func TestTransferInsufficientFundsTouchesNothingElse(t *testing.T) {
	ctrl := gomock.NewController(t)
	l := NewMockLedger(ctrl)
	l.EXPECT().Balance(gomock.Any(), "a").Return(int64(10), nil)
	// No other EXPECT: an unexpected Debit or Credit fails the test.

	if err := Transfer(t.Context(), l, "a", "b", 300); !errors.Is(err, ErrInsufficient) {
		t.Fatalf("err = %v", err)
	}
}

Interface embedding Good to know ​

In plain words: Embedding an interface in another interface joins their method sets. Embedding an interface in a struct lets the struct satisfy a wide interface while writing only the methods a test needs.

Common misunderstanding: "An embedded-interface fake is safe because it compiles." The embedded value is nil unless you set it, so any method you did not override panics with a nil pointer dereference. That is useful as a tripwire ("this test must not call Put"), harmful if you forget.

Definition: type Store interface { Reader; Writer } is interface embedding (composition of small interfaces, as io.ReadWriter does). type partialFake struct{ Store; gets int } is struct embedding of an interface: promoted methods call the embedded value. See Structs, Methods, Embedding.

1  type Store interface { Reader; Writer }          methods: Get, Put
2  type partialFake struct{ Store }                 satisfies Store (Get, Put promoted)
3  func (p *partialFake) Get(...)                   override only Get
4  Describe(p, "k", false)  -> "canned"             Put never called: fine
5  Describe(p, "k", true)   -> panic: nil pointer   Put promoted from a nil Store

Real scenario: a 15-method Repository where the test needs FindByID; an HTTP middleware test that embeds http.ResponseWriter to intercept WriteHeader; a *sql.Tx wrapper that overrides Commit.

FormEffectRisk
Interface in interfaceUnion of method setsNone
Interface in struct (partial fake)Satisfies the interface cheaplyNil panic for unfaked methods
Struct in struct (embedding)Promotes methods and fieldsName clashes

Fix / how to use it: use embedding for partial fakes of wide third-party interfaces; prefer splitting your own interface instead.

go
// Package ifacepitfalls collects the interface behaviours that surprise people
// when they start writing doubles: typed nil, embedding and producer-side
// interfaces.
package ifacepitfalls

import "fmt"

// ValidationError is a custom error type with a pointer receiver.
type ValidationError struct{ Field string }

func (e *ValidationError) Error() string { return "invalid " + e.Field }

// Validate is WRONG: it returns a typed nil pointer in an error interface.
// The interface value is (type *ValidationError, value nil), which is != nil.
func Validate(name string) error {
	var ve *ValidationError
	if name == "" {
		ve = &ValidationError{Field: "name"}
	}
	return ve // BUG: never a nil interface
}

// ValidateFixed returns an untyped nil when there is no error.
func ValidateFixed(name string) error {
	if name == "" {
		return &ValidationError{Field: "name"}
	}
	return nil
}

// Reader and Writer are two small interfaces; Store composes them.
type Reader interface {
	Get(key string) (string, bool)
}

// Writer is the write half.
type Writer interface{ Put(key, value string) }

// Store is interface embedding: the method set is the union.
type Store interface {
	Reader
	Writer
}

// mapStore is the full implementation.
type mapStore map[string]string

func (m mapStore) Get(k string) (string, bool) { v, ok := m[k]; return v, ok }
func (m mapStore) Put(k, v string)             { m[k] = v }

// NewStore returns a ready Store.
func NewStore() Store { return mapStore{} }

// partialFake embeds the interface so it satisfies Store while overriding one
// method. Any method it does not override calls through the nil embedded value
// and panics, which flags an unexpected dependency loudly.
type partialFake struct {
	Store
	gets int
}

func (p *partialFake) Get(k string) (string, bool) { p.gets++; return "canned", true }

// Describe reads a value and optionally writes back. Used by the tests.
func Describe(s Store, key string, writeBack bool) string {
	v, _ := s.Get(key)
	if writeBack {
		s.Put(key, v+"!")
	}
	return fmt.Sprint(v)
}

// Thing is what a producer package hands out. Returning the concrete type
// keeps every method reachable; returning an interface hides new ones.
type Thing struct{ n int }

// Value is part of the narrow interface.
func (t *Thing) Value() int { return t.n }

// Reset was added later; callers holding a concrete *Thing can use it at once.
func (t *Thing) Reset() { t.n = 0 }

// NewThing returns the concrete type, as the Go Code Review Comments advise.
func NewThing(n int) *Thing { return &Thing{n: n} }

// Valuer is what a consumer would declare for itself.
type Valuer interface{ Value() int }

// NewValuer is the discouraged producer-side shape: the interface is declared
// next to the implementation "for mocking".
func NewValuer(n int) Valuer { return &Thing{n: n} }
go
package ifacepitfalls

import (
	"fmt"
	"testing"
)

func TestTypedNilIsNotNilInterface(t *testing.T) {
	err := Validate("ada") // no problem with the input...
	if err == nil {
		t.Fatal("expected the typed-nil trap: err != nil even though nothing is wrong")
	}
	// The dynamic type is set, the pointer inside is nil.
	if fmt.Sprintf("%T", err) != "*ifacepitfalls.ValidationError" {
		t.Fatalf("type = %T", err)
	}
	if err := ValidateFixed("ada"); err != nil {
		t.Fatalf("fixed version returned %v", err)
	}
	if err := ValidateFixed(""); err == nil {
		t.Fatal("want an error for empty name")
	}
}

func TestEmbeddedInterfaceFake(t *testing.T) {
	p := &partialFake{}

	if got := Describe(p, "k", false); got != "canned" {
		t.Fatalf("got %q", got)
	}

	// Put was not overridden: the nil embedded Store panics.
	defer func() {
		if recover() == nil {
			t.Fatal("expected a nil pointer panic from the un-faked Put")
		}
	}()
	Describe(p, "k", true)
}

func TestInterfaceEmbeddingComposesMethodSets(t *testing.T) {
	var s Store = NewStore()
	s.Put("a", "1")
	var r Reader = s // a Store is also a Reader
	if v, ok := r.Get("a"); !ok || v != "1" {
		t.Fatalf("Get = %q, %v", v, ok)
	}
}

func TestProducerSideInterfaceHidesMethods(t *testing.T) {
	concrete := NewThing(5)
	concrete.Reset() // reachable: new methods need no refactoring
	if concrete.Value() != 0 {
		t.Fatal("Reset did nothing")
	}

	hidden := NewValuer(5)
	if _, ok := hidden.(interface{ Reset() }); !ok {
		t.Fatal("this assertion works only because we know the concrete type")
	}
	// hidden.Reset() does not compile: Valuer has no Reset.
}

Nil interface vs typed nil Important ​

In plain words: An interface value is two things: a type and a value. It is nil only when both are empty. A nil pointer stored in an interface has a type, so the interface is not nil.

Common misunderstanding: "If the pointer inside is nil, the interface is nil." The Go FAQ answers this: "An interface value is nil only if the V and T are both unset" and "Such an interface value will therefore be non-nil even when the pointer value V inside is nil."

Definition: var ve *ValidationError; return ve from a function returning error yields (T=*ValidationError, V=nil), which is != nil. It shows up in injection code when a constructor or fake returns a typed nil as an interface, or when a double's method returns a concrete error pointer.

1  var ve *ValidationError           ve == nil (pointer)
2  var err error = ve                err == nil ?  false   (T=*ValidationError, V=nil)
3  if err != nil { ... }             taken, even though "no error"
4  fix: return nil                   (T=nil, V unset) -> err == nil is true

Real scenario: a validator returning *MultiError that is sometimes nil; a mock Return(nil) of the wrong type; a factory returning *Client assigned to a Client interface and tested with == nil; a generic helper that wraps a pointer.

CodeInterface value== nil
var e error(nil, unset)true
var p *MyErr; var e error = p(*MyErr, nil)false
return nil in func f() error(nil, unset)true
return p where p is a nil *MyErr(*MyErr, nil)false

Fix / how to use it: return the interface type's nil literal on the success path; never return a typed pointer variable that might be nil. The Validate / ValidateFixed pair in the snippet above is tested to prove both. See Interfaces, Type Assertions, Type Switches & any.

Manual DI, the dependency graph and the composition root Must-know ​

In plain words: Somewhere in the program, one piece of code must know every concrete type and plug them together. That place is the composition root, and in a Go program it is main (or a Build function called by main). Everything else only sees interfaces.

Common misunderstanding: "Wiring can live anywhere that needs the object." If a handler constructs its own repository, it is no longer injectable. Constructing objects is the root's job; using them is everyone else's.

Definition: the dependency graph is the directed graph whose nodes are constructors and whose edges are parameters. Manual DI writes the graph out by hand, leaves first. "package main wiring" means main reads configuration, calls the root, and owns only process concerns (signals, listening, shutdown). The run(ctx, getenv) pattern makes main testable: run takes everything it needs as parameters, so a test calls it with a map and a cancellable context.

1  main:      ctx, stop := signal.NotifyContext(...)
2  main:      run(ctx, os.Getenv)
3  run:       cfg := wiring.Config{PaymentURL: getenv("PAYMENT_URL")}
4  run:       app := wiring.Build(cfg, &http.Client{Timeout: 5*time.Second})
5  Build:     store -> gateway -> service -> handler -> mux           (leaves first)
6  run:       srv.ListenAndServe(); on ctx.Done(): srv.Shutdown(WithoutCancel ctx + 10s)

Real scenario: a REST API (see A REST API in Go) whose main builds pool, repositories, services and handlers in 40 lines; a worker binary and an API binary sharing one Build for the common core; an end-to-end test that calls Build with an httptest payment server.

QuestionAnswer
Who may call New... for a concrete type?The composition root, and tests
Where does configuration get parsed?main, then passed into Build as a struct
How do I test the whole graph?Call Build with fakes at the edges (see snippet)
What if Build grows to 200 lines?Split by module, or consider wire/fx
Where do goroutine lifecycles go?main/run: start, Shutdown on cancel (OS Processes & Graceful Shutdown)

Fix / how to use it: write the graph by hand until it hurts. The snippet's Build is 6 lines; the test exercises routing, status mapping and storage through the real graph with one fake edge.

go
// Package wiring is the composition root done by hand: the one place that
// knows every concrete type and builds the whole dependency graph.
package wiring

import (
	"context"
	"encoding/json"
	"errors"
	"net/http"
	"strconv"

	"academy/mocking-interfaces-di/after"
)

// Config is everything that comes from the environment.
type Config struct {
	PaymentURL string
}

// Checkouter is the consumer-defined interface the HTTP layer needs.
type Checkouter interface {
	Checkout(ctx context.Context, id string, cents int) (after.Order, error)
}

// OrderHandler is the HTTP adapter. It knows nothing about stores or gateways.
type OrderHandler struct{ svc Checkouter }

// NewOrderHandler wires the use case into HTTP.
func NewOrderHandler(svc Checkouter) *OrderHandler { return &OrderHandler{svc: svc} }

// Create handles POST /orders/{id}?cents=1250.
func (h *OrderHandler) Create(w http.ResponseWriter, r *http.Request) {
	cents, err := strconv.Atoi(r.URL.Query().Get("cents"))
	if err != nil {
		http.Error(w, "cents must be an integer", http.StatusBadRequest)
		return
	}
	o, err := h.svc.Checkout(r.Context(), r.PathValue("id"), cents)
	switch {
	case err == nil:
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusCreated)
		_ = json.NewEncoder(w).Encode(map[string]any{"id": o.ID, "payment": o.PaymentID})
	case isDeclined(err):
		http.Error(w, "payment declined", http.StatusPaymentRequired)
	default:
		http.Error(w, "internal error", http.StatusInternalServerError)
	}
}

// Routes registers the handler on a Go 1.22+ pattern mux.
func (h *OrderHandler) Routes() http.Handler {
	mux := http.NewServeMux()
	mux.HandleFunc("POST /orders/{id}", h.Create)
	return mux
}

// App is the assembled program.
type App struct {
	Handler http.Handler
	Store   *after.MemStore
}

// Build is the composition root: leaf dependencies first, then the things
// that need them, then the entry point. Nothing outside this function (and
// main, which calls it) names a concrete implementation.
func Build(cfg Config, client *http.Client) *App {
	store := after.NewMemStore()
	gateway := after.HTTPGateway{BaseURL: cfg.PaymentURL, Client: client}
	svc := after.NewService(store, gateway)
	handler := NewOrderHandler(svc)
	return &App{Handler: handler.Routes(), Store: store}
}

func isDeclined(err error) bool { return errors.Is(err, after.ErrDeclined) }
go
package wiring

import (
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
)

// fakePayments is an httptest server standing in for the payment provider.
func fakePayments(t *testing.T, status int) *httptest.Server {
	t.Helper()
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if status != http.StatusOK {
			w.WriteHeader(status)
			return
		}
		_, _ = w.Write([]byte(`{"id":"pay-9"}`))
	}))
	t.Cleanup(srv.Close)
	return srv
}

// Whole-graph test: the real Build, the real service and handler, with the
// one edge that leaves the process replaced by a fake server.
func TestBuildEndToEnd(t *testing.T) {
	t.Run("created", func(t *testing.T) {
		pay := fakePayments(t, http.StatusOK)
		app := Build(Config{PaymentURL: pay.URL}, pay.Client())

		rec := httptest.NewRecorder()
		app.Handler.ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/orders/o-1?cents=1250", nil))

		if rec.Code != http.StatusCreated || !strings.Contains(rec.Body.String(), "pay-9") {
			t.Fatalf("code=%d body=%s", rec.Code, rec.Body)
		}
		if o, ok := app.Store.Get("o-1"); !ok || o.Cents != 1250 {
			t.Fatalf("stored = %+v, %v", o, ok)
		}
	})
	t.Run("declined maps to 402 and stores nothing", func(t *testing.T) {
		pay := fakePayments(t, http.StatusPaymentRequired)
		app := Build(Config{PaymentURL: pay.URL}, pay.Client())

		rec := httptest.NewRecorder()
		app.Handler.ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/orders/o-2?cents=500", nil))

		if rec.Code != http.StatusPaymentRequired {
			t.Fatalf("code = %d", rec.Code)
		}
		if _, ok := app.Store.Get("o-2"); ok {
			t.Fatal("declined order must not be stored")
		}
	})
	t.Run("bad input", func(t *testing.T) {
		app := Build(Config{PaymentURL: "http://unused.invalid"}, http.DefaultClient)
		rec := httptest.NewRecorder()
		app.Handler.ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/orders/o-3?cents=abc", nil))
		if rec.Code != http.StatusBadRequest {
			t.Fatalf("code = %d", rec.Code)
		}
	})
}
go
// Command server is "package main wiring": main reads the environment, asks
// the composition root for the graph, and owns process-level concerns only
// (signals, listening, shutdown).
package main

import (
	"context"
	"errors"
	"fmt"
	"log/slog"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"academy/mocking-interfaces-di/wiring"
)

func main() {
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
	defer stop()
	if err := run(ctx, os.Getenv); err != nil {
		slog.Error("server stopped", "err", err)
		os.Exit(1)
	}
}

// run takes everything it needs as parameters (a context and a getenv
// function), so a test can call it without touching the real environment.
func run(ctx context.Context, getenv func(string) string) error {
	cfg := wiring.Config{PaymentURL: getenv("PAYMENT_URL")}
	if cfg.PaymentURL == "" {
		return errors.New("PAYMENT_URL is required")
	}
	addr := getenv("ADDR")
	if addr == "" {
		addr = "127.0.0.1:8080"
	}

	app := wiring.Build(cfg, &http.Client{Timeout: 5 * time.Second})
	srv := &http.Server{Addr: addr, Handler: app.Handler, ReadHeaderTimeout: 5 * time.Second}

	errc := make(chan error, 1)
	go func() { errc <- srv.ListenAndServe() }()

	select {
	case err := <-errc:
		return err
	case <-ctx.Done():
		shutdownCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second)
		defer cancel()
		if err := srv.Shutdown(shutdownCtx); err != nil {
			return fmt.Errorf("shutdown: %w", err)
		}
		return nil
	}
}
go
package main

import (
	"context"
	"strings"
	"testing"
	"time"
)

func TestRunRejectsMissingConfig(t *testing.T) {
	err := run(t.Context(), func(string) string { return "" })
	if err == nil || !strings.Contains(err.Error(), "PAYMENT_URL") {
		t.Fatalf("err = %v", err)
	}
}

func TestRunStopsOnCancel(t *testing.T) {
	env := map[string]string{"PAYMENT_URL": "http://payments.invalid", "ADDR": "127.0.0.1:0"}
	ctx, cancel := context.WithCancel(t.Context())
	done := make(chan error, 1)
	go func() { done <- run(ctx, func(k string) string { return env[k] }) }()

	time.Sleep(50 * time.Millisecond) // let ListenAndServe start
	cancel()

	select {
	case err := <-done:
		if err != nil {
			t.Fatalf("run returned %v after cancel", err)
		}
	case <-time.After(5 * time.Second):
		t.Fatal("run did not return after cancel")
	}
}
Composition root: build the graph once, at the edgefunc main() / run(ctx, getenv)reads env, owns signals and shutdown, calls Buildcomposition root: Build(cfg, client) (the only place that names concrete types)MemStore / pgx poolleafHTTPGatewayleaf (needs client)ServiceNewService(store, pay)OrderHandlerNewOrderHandler(svc)order of construction = order of the dependency graph, leaves firstwire generates this body at build time; fx works it out at start-up by reflectionproduction: real store, real gatewaytest: same Build, httptest server or fake at the edges

wire (google/wire) Important ​

In plain words: wire writes your Build function for you at build time. You list the constructors (providers) and say what you want; it generates plain Go that calls them in the right order, or tells you something is missing.

Common misunderstanding: "wire is a runtime container like Spring." It is a code generator: no reflection at run time, no magic after generation, and a missing dependency is a generator error, not a production panic.

Definition: the user guide says "Wire has two core concepts: providers and injectors." A provider is an ordinary function that returns a value; providers group into sets with wire.NewSet. "An injector is declared by writing a function declaration whose body is a call to wire.Build", in a file with the build tag wireinject; the wire command generates wire_gen.go. The package also offers wire.Bind(new(Iface), new(*Impl)), wire.Struct(new(T), "*"), wire.Value, wire.InterfaceValue and wire.FieldsOf, and cleanup functions returned as a second value. Variadic parameters (...Option) cannot be injected, so the snippet wraps NewService in ProvideService. The CLI here was wire v0.7.0, built outside the module because the v0.6.0 tool pins an x/tools that does not compile on Go 1.27.4; the library in go.mod is v0.6.0.

1  providers.go   ProvideStore, ProvideGateway(cfg, client), ProvideService(store, pay)
2  providers.go   ServiceSet = wire.NewSet(..., wire.Bind(new(after.OrderStore), new(*after.MemStore)), ...)
3  wire.go        //go:build wireinject   func InitializeService(cfg, client) *after.Service { wire.Build(ServiceSet); return nil }
4  $ wire         -> writes wire_gen.go
5  wire_gen.go    memStore := ProvideStore(); httpGateway := ProvideGateway(cfg, client); service := ProvideService(memStore, httpGateway)

Real scenario: a monorepo with five binaries sharing 60 providers; a service where cmd/api and cmd/worker build different subsets of one set; a team that wants a CI failure when a new constructor parameter is not provided.

FeatureBehaviour
Time of workBuild time (generator)
Run-time costNone: the output is plain Go
Missing providerwire reports it while generating
Interface bindingwire.Bind
Lifecycle (start/stop)Cleanup functions only; no hooks
DebuggingRead wire_gen.go

Fix / how to use it: keep providers small and sets per module; commit wire_gen.go; test the injector like any function (TestInitializeService).

go
// Package wiredi builds the same graph with google/wire. The injector in
// wire.go is only a description; wire_gen.go is generated from it.
package wiredi

import (
	"net/http"

	"github.com/google/wire"

	"academy/mocking-interfaces-di/after"
)

// Config is the input to the injector.
type Config struct{ PaymentURL string }

// ProvideStore is a provider: an ordinary function that produces a value.
func ProvideStore() *after.MemStore { return after.NewMemStore() }

// ProvideGateway turns config and a client into the production gateway.
func ProvideGateway(cfg Config, client *http.Client) after.HTTPGateway {
	return after.HTTPGateway{BaseURL: cfg.PaymentURL, Client: client}
}

// ProvideService wraps after.NewService, whose variadic options wire cannot inject.
func ProvideService(store after.OrderStore, pay after.PaymentGateway) *after.Service {
	return after.NewService(store, pay)
}

// ServiceSet groups the providers and binds interfaces to implementations.
var ServiceSet = wire.NewSet(
	ProvideStore,
	wire.Bind(new(after.OrderStore), new(*after.MemStore)),
	ProvideGateway,
	wire.Bind(new(after.PaymentGateway), new(after.HTTPGateway)),
	ProvideService,
)
go
//go:build wireinject

package wiredi

import (
	"net/http"

	"github.com/google/wire"

	"academy/mocking-interfaces-di/after"
)

// InitializeService is an injector: the body is a call to wire.Build and the
// return statement only satisfies the compiler.
func InitializeService(cfg Config, client *http.Client) *after.Service {
	wire.Build(ServiceSet)
	return nil
}
go
// Code generated by Wire. DO NOT EDIT.

//go:generate go run -mod=mod github.com/google/wire/cmd/wire
//go:build !wireinject
// +build !wireinject

package wiredi

import (
	"academy/mocking-interfaces-di/after"
	"net/http"
)

// Injectors from wire.go:

// InitializeService is an injector: the body is a call to wire.Build and the
// return statement only satisfies the compiler.
func InitializeService(cfg Config, client *http.Client) *after.Service {
	memStore := ProvideStore()
	httpGateway := ProvideGateway(cfg, client)
	service := ProvideService(memStore, httpGateway)
	return service
}
go
package wiredi

import (
	"net/http"
	"net/http/httptest"
	"testing"
)

// The generated injector is ordinary code, so it is tested like any function.
func TestInitializeService(t *testing.T) {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		_, _ = w.Write([]byte(`{"id":"pay-3"}`))
	}))
	defer srv.Close()

	svc := InitializeService(Config{PaymentURL: srv.URL}, srv.Client())
	o, err := svc.Checkout(t.Context(), "o-1", 700)
	if err != nil || o.PaymentID != "pay-3" {
		t.Fatalf("order=%+v err=%v", o, err)
	}
}

fx (uber) Important ​

In plain words: fx is a runtime DI framework from Uber. You register constructors with fx.Provide, run things with fx.Invoke, and fx figures out the order by reflection when the app starts. It also manages start and stop hooks.

Common misunderstanding: "fx is just wire at run time." It also owns the application lifecycle (fx.Lifecycle hooks with OnStart and OnStop), logging, and modules. Missing dependencies fail at start-up, not at compile time, unless you call fx.ValidateApp in a test.

Definition: the README says "Fx is a dependency injection system for Go", with the benefit "Eliminate globals: Fx helps you remove global state from your application. No more init() or global variables." It is built on go.uber.org/dig. In the snippet, fx.Annotate(after.NewMemStore, fx.As(new(after.OrderStore))) binds the concrete type to the interface, fx.Supply provides ready values, fx.Populate copies a result out for tests, and fx.ValidateApp checks the graph without running it. fx.NopLogger silences its start-up log.

1  fx.New(fx.Supply(cfg, client), fx.Provide(annotated constructors...), fx.Populate(&svc))
2  app.Start(ctx)          runs OnStart hooks in dependency order
3  svc.Checkout(...)       your code runs
4  app.Stop(ctx)           runs OnStop hooks in reverse order
5  fx.ValidateApp(Module, fx.Supply(Config{}), fx.Invoke(func(*after.Service){}))  -> error: no *http.Client provided

Real scenario: a large service fleet with common modules for logging, metrics and HTTP; a binary with many background workers that need ordered start and graceful stop; a test that ValidateApps the production module in CI.

Questionwirefx
When are errors found?GenerationValidateApp or start-up
ReflectionNone at run timeYes (through dig)
Lifecycle hooksNoYes
Generated code to reviewYesNo
Learning curveSmallLarger (annotations, groups, modules)
Dependencies addedgithub.com/google/wirego.uber.org/fx, dig, zap

Fix / how to use it: adopt fx when lifecycle ordering is the pain, wire when graph size is; for most services a hand-written Build is enough.

go
// Package fxapp builds the same graph with uber-go/fx. Constructors are
// registered with fx.Provide and fx resolves the order at runtime by
// reflection (through go.uber.org/dig).
package fxapp

import (
	"net/http"

	"go.uber.org/fx"

	"academy/mocking-interfaces-di/after"
)

// Config is supplied with fx.Supply.
type Config struct{ PaymentURL string }

func newGateway(cfg Config, client *http.Client) after.HTTPGateway {
	return after.HTTPGateway{BaseURL: cfg.PaymentURL, Client: client}
}

func newService(store after.OrderStore, pay after.PaymentGateway) *after.Service {
	return after.NewService(store, pay)
}

// Module is the reusable group of providers.
var Module = fx.Options(
	fx.Provide(
		fx.Annotate(after.NewMemStore, fx.As(new(after.OrderStore))),
		fx.Annotate(newGateway, fx.As(new(after.PaymentGateway))),
		newService,
	),
)

// New returns an app that exposes the service through target.
func New(cfg Config, client *http.Client, target **after.Service, extra ...fx.Option) *fx.App {
	opts := []fx.Option{
		fx.NopLogger,
		fx.Supply(cfg, client),
		Module,
		fx.Populate(target),
	}
	return fx.New(append(opts, extra...)...)
}
go
package fxapp

import (
	"context"
	"net/http"
	"net/http/httptest"
	"testing"
	"time"

	"go.uber.org/fx"

	"academy/mocking-interfaces-di/after"
)

func TestGraphStartsAndStops(t *testing.T) {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		_, _ = w.Write([]byte(`{"id":"pay-5"}`))
	}))
	defer srv.Close()

	var svc *after.Service
	app := New(Config{PaymentURL: srv.URL}, srv.Client(), &svc)

	ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)
	defer cancel()
	if err := app.Start(ctx); err != nil {
		t.Fatal(err)
	}
	defer func() { _ = app.Stop(ctx) }()

	o, err := svc.Checkout(ctx, "o-1", 900)
	if err != nil || o.PaymentID != "pay-5" {
		t.Fatalf("order=%+v err=%v", o, err)
	}
}

// ValidateApp checks that every constructor's inputs can be satisfied without
// running anything: a missing provider fails here, in CI, not in production.
func TestValidateAppCatchesMissingProvider(t *testing.T) {
	if err := fx.ValidateApp(Module, fx.Supply(Config{}), fx.Invoke(func(*after.Service) {})); err == nil {
		t.Fatal("want an error: *http.Client was never provided")
	}
	if err := fx.ValidateApp(Module, fx.Supply(Config{}, &http.Client{}), fx.Invoke(func(*after.Service) {})); err != nil {
		t.Fatalf("complete graph must validate: %v", err)
	}
}

Globals, init() and singletons Must-know ​

In plain words: A global variable set in init() is a dependency nobody can see in a function's signature and nobody can replace without editing shared state. A singleton does the same through a getter.

Common misunderstanding: "sync.Once makes the singleton safe, so it is fine." It makes initialisation race-free, not testable: the instance survives from one test to the next, so state leaks. The fx README lists the opposite goal: "No more init() or global variables."

Definition: the antipatterns snippet has an init() that installs an SMTP mailer at import time, NotifyGlobal that uses it, Instance() returning a process-wide counter, and a constructor-injected Notifier as the fix. Tests of the global version must patch and restore (SetDefaultMailerForTest) and cannot be parallel; a forgotten defer restore() poisons later tests.

1  import academy/antipatterns          init() runs: defaultMailer = &smtpMailer{...}
2  TestA: NotifyGlobal(...)             uses the init()-installed smtpMailer (its Send fails: "dial smtp.example.test: refused")
3  TestB: Instance().Inc() == 1         passes alone
4  TestC: Instance().Inc() == 1         fails after TestB: shared counter
5  fix:   NewNotifier(mailer)           per-test instance, no restore, t.Parallel() allowed

Real scenario: a package-level var db *sql.DB assigned in init(); a logger.Get() singleton; a package-level http.Client with a timeout nobody can change; a metrics registry in a global.

PatternInvisible dependencyParallel testsReplace in test
Constructor injectionNoYesPass a double
Package variable set in mainYesNoPatch and restore
init() side effectsYesNoOften impossible
Singleton via sync.OnceYesState leaksNeeds a reset hook
Stdlib globals (http.DefaultClient)YesSharedPass your own client

Fix / how to use it: keep init() for registering drivers and flags only; build everything else in main. See Toolchain, Modules & Packages.

Service locator Important ​

In plain words: A service locator is a registry you ask for things by name inside your code: registry.Get("mailer"). It looks like injection but hides dependencies inside function bodies.

Common misunderstanding: "A registry is just a container, same as DI." Fowler's article draws the line: with a locator the component asks for its collaborators; with DI they are handed to it. The practical difference: a missing dependency is a compile error with a constructor and a run-time error with a locator.

Definition: Registry.Get(name) (any, error) returns any, so the caller must assert the type, and NotifyViaLocator can fail with "service "mailer" is not registered" or "is *T, not a Mailer" in production. It also couples every package to the registry.

1  NotifyViaLocator(r, to)           signature says: needs a *Registry (nothing about a Mailer)
2  r.Get("mailer")                   error: not registered           (found at run time)
3  r.Register("mailer", "oops")      wrong type registered
4  svc.(Mailer)                      error: not a Mailer             (found at run time)
5  NewNotifier(m Mailer)             missing or wrong type does not compile

Real scenario: a global container.Get[T]() helper; a ctx.Value(serviceKey) lookup; a plugin registry used from business code; an app.Services["db"] map.

PropertyService locatorConstructor injection
Dependencies visible in signatureNoYes
Missing dependency foundRun timeCompile time
Type safetyAssertionsStatic
Test setupRegister doubles in a registryPass doubles
Legitimate usePlugin systems, database/sql driver registryEverything else

Fix / how to use it: if you have a locator, confine it to the composition root and pass the resolved values onward.

go
// Package antipatterns shows the three shapes that make code hard to test:
// package-level state set in init(), a singleton accessor, and a service
// locator. The tests show what each costs.
package antipatterns

import (
	"fmt"
	"sync"
)

// Mailer sends mail.
type Mailer interface{ Send(to string) error }

// --- 1. globals and init() ---------------------------------------------------

var defaultMailer Mailer

func init() {
	// Runs at import time, in every binary and every test that imports the
	// package, with no way to pass configuration or return an error.
	defaultMailer = &smtpMailer{host: "smtp.example.test"}
}

type smtpMailer struct{ host string }

func (m *smtpMailer) Send(to string) error { return fmt.Errorf("dial %s: refused", m.host) }

// NotifyGlobal reaches for the global: the dependency is invisible in the signature.
func NotifyGlobal(to string) error { return defaultMailer.Send(to) }

// SetDefaultMailerForTest is the usual escape hatch: tests mutate the global
// and must restore it, and cannot run in parallel.
func SetDefaultMailerForTest(m Mailer) (restore func()) {
	old := defaultMailer
	defaultMailer = m
	return func() { defaultMailer = old }
}

// --- 2. singleton ----------------------------------------------------------------

var (
	once     sync.Once
	instance *Counter
)

// Counter is a process-wide counter.
type Counter struct {
	mu sync.Mutex
	n  int
}

// Instance returns the one Counter; state leaks from one test to the next.
func Instance() *Counter {
	once.Do(func() { instance = &Counter{} })
	return instance
}

// Inc increments and returns the new value.
func (c *Counter) Inc() int {
	c.mu.Lock()
	defer c.mu.Unlock()
	c.n++
	return c.n
}

// --- 3. service locator --------------------------------------------------------------

// Registry is a service locator: a bag of named services.
type Registry struct {
	mu       sync.RWMutex
	services map[string]any
}

// NewRegistry returns an empty locator.
func NewRegistry() *Registry { return &Registry{services: map[string]any{}} }

// Register stores a service under a name.
func (r *Registry) Register(name string, svc any) {
	r.mu.Lock()
	defer r.mu.Unlock()
	r.services[name] = svc
}

// Get returns a service or an error: a missing dependency is discovered when
// this line runs, not when the program compiles.
func (r *Registry) Get(name string) (any, error) {
	r.mu.RLock()
	defer r.mu.RUnlock()
	svc, ok := r.services[name]
	if !ok {
		return nil, fmt.Errorf("service %q is not registered", name)
	}
	return svc, nil
}

// NotifyViaLocator hides its needs inside the body.
func NotifyViaLocator(r *Registry, to string) error {
	svc, err := r.Get("mailer")
	if err != nil {
		return err
	}
	m, ok := svc.(Mailer)
	if !ok {
		return fmt.Errorf("service %q is %T, not a Mailer", "mailer", svc)
	}
	return m.Send(to)
}

// --- the fix ------------------------------------------------------------------------------

// Notifier states its dependency in its constructor: the compiler checks it.
type Notifier struct{ m Mailer }

// NewNotifier requires a Mailer; there is no way to forget it.
func NewNotifier(m Mailer) *Notifier { return &Notifier{m: m} }

// Notify sends mail through the injected Mailer.
func (n *Notifier) Notify(to string) error { return n.m.Send(to) }
go
package antipatterns

import (
	"errors"
	"strings"
	"testing"
)

type recordingMailer struct{ sent []string }

func (r *recordingMailer) Send(to string) error { r.sent = append(r.sent, to); return nil }

func TestGlobalNeedsPatchAndRestore(t *testing.T) {
	// init() already ran and installed the SMTP mailer: with no patching the
	// "unit" test exercises the SMTP-backed mailer (here its Send just returns a "dial ... refused" error; a real sender would open a connection).
	if err := NotifyGlobal("a@example.test"); err == nil || !strings.Contains(err.Error(), "smtp.example.test") {
		t.Fatalf("expected the init()-installed mailer to be used, got %v", err)
	}

	rec := &recordingMailer{}
	restore := SetDefaultMailerForTest(rec)
	defer restore() // forget this and every later test inherits the double
	if err := NotifyGlobal("a@example.test"); err != nil || len(rec.sent) != 1 {
		t.Fatalf("sent=%v err=%v", rec.sent, err)
	}
}

func TestSingletonLeaksStateBetweenTests(t *testing.T) {
	first := Instance().Inc()
	second := Instance().Inc()
	if second != first+1 {
		t.Fatalf("first=%d second=%d: the counter is shared by everything in the process", first, second)
	}
	// A test that expects the counter to start at 0 passes alone and fails
	// after any other test touched Instance().
}

func TestServiceLocatorFailsAtRuntime(t *testing.T) {
	r := NewRegistry()
	if err := NotifyViaLocator(r, "a@example.test"); err == nil || !strings.Contains(err.Error(), "not registered") {
		t.Fatalf("err = %v", err)
	}
	r.Register("mailer", "oops, a string")
	if err := NotifyViaLocator(r, "a@example.test"); err == nil || !strings.Contains(err.Error(), "not a Mailer") {
		t.Fatalf("err = %v", err)
	}
	rec := &recordingMailer{}
	r.Register("mailer", rec)
	if err := NotifyViaLocator(r, "a@example.test"); err != nil || len(rec.sent) != 1 {
		t.Fatalf("sent=%v err=%v", rec.sent, err)
	}
}

func TestConstructorInjectionNeedsNoPatching(t *testing.T) {
	t.Parallel()
	boom := errors.New("smtp down")
	n := NewNotifier(failingMailer{boom})
	if err := n.Notify("a@example.test"); !errors.Is(err, boom) {
		t.Fatalf("err = %v", err)
	}
	// NewNotifier(nil) compiles, but the dependency is at least visible in the
	// signature; the missing-argument case does not compile at all.
}

type failingMailer struct{ err error }

func (f failingMailer) Send(string) error { return f.err }

Contract tests and golden fakes shared with production Important ​

In plain words: A fake is only useful while it behaves like the real thing. A contract test is one test suite that every implementation of an interface must pass, the fake included, so the fake cannot quietly drift.

Common misunderstanding: "The fake is test code, so nobody needs to test it." If the fake returns nil for a missing key while the real store returns ErrNotFound, every test built on the fake is lying. The standard library does this itself: testing/fstest ships TestFS, a checker that validates any fs.FS implementation.

Definition: storetest.Run(t, newStore) holds the behavioural contract (missing key is ErrNotFound, Put overwrites, Delete is idempotent, Keys are sorted). It runs against MemStore (the fake) and FileStore (a durable stand-in for a database). A "golden fake" is a fake that ships with the production package, is held to the contract, and is the one every consumer uses. For a real database you add a third run of the same suite against PostgreSQL started by testcontainers; this page only names that option.

1  func TestMemStoreContract(t)   storetest.Run(t, newMemStore)
2  func TestFileStoreContract(t)  storetest.Run(t, newFileStore(t.TempDir()))
3  future:  TestPostgresContract  storetest.Run(t, newPgStore(container))     (not run here)
4  fake changes: Delete(missing) returns error   -> "delete is idempotent" fails in the fake's own test

Real scenario: a payment-provider fake used by 30 services; an in-memory queue used in unit tests and a real broker in integration tests; a clock fake checked against time.Time arithmetic; a cache fake checked against Redis semantics.

Without a contractWith a contract
Fake and real drift silentlyDivergence fails a test
Each service re-writes its own fakeOne shared fake
Integration tests find the gaps lateUnit-level contract finds them early
Cost: none up frontCost: one suite per interface

Fix / how to use it: write the contract for interfaces with several implementations (store, queue, cache). Use t.TempDir() for file-backed ones.

go
// Package storefake has one Store interface, two real implementations and a
// shared contract (storetest) that both must pass. The in-memory MemStore is a
// "golden fake": it ships next to production code and is held to the same
// behaviour as the durable implementation.
package storefake

import (
	"encoding/json"
	"errors"
	"fmt"
	"os"
	"sort"
	"sync"
)

// ErrNotFound is returned by Get for a missing key.
var ErrNotFound = errors.New("not found")

// Store is a tiny key-value store.
type Store interface {
	Get(key string) (string, error)
	Put(key, value string) error
	Delete(key string) error
	Keys() ([]string, error)
}

// MemStore keeps everything in a map.
type MemStore struct {
	mu sync.Mutex
	m  map[string]string
}

// NewMemStore returns an empty MemStore.
func NewMemStore() *MemStore { return &MemStore{m: map[string]string{}} }

// Get implements Store.
func (s *MemStore) Get(k string) (string, error) {
	s.mu.Lock()
	defer s.mu.Unlock()
	v, ok := s.m[k]
	if !ok {
		return "", ErrNotFound
	}
	return v, nil
}

// Put implements Store.
func (s *MemStore) Put(k, v string) error {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.m[k] = v
	return nil
}

// Delete implements Store; deleting a missing key is not an error.
func (s *MemStore) Delete(k string) error {
	s.mu.Lock()
	defer s.mu.Unlock()
	delete(s.m, k)
	return nil
}

// Keys implements Store and returns the keys sorted.
func (s *MemStore) Keys() ([]string, error) {
	s.mu.Lock()
	defer s.mu.Unlock()
	keys := make([]string, 0, len(s.m))
	for k := range s.m {
		keys = append(keys, k)
	}
	sort.Strings(keys)
	return keys, nil
}

// FileStore persists the whole map as JSON on every write. It stands in for a
// real database here: slow, simple, durable.
type FileStore struct {
	mu   sync.Mutex
	path string
}

// NewFileStore uses path, creating it on first write.
func NewFileStore(path string) *FileStore { return &FileStore{path: path} }

func (s *FileStore) load() (map[string]string, error) {
	data, err := os.ReadFile(s.path)
	if errors.Is(err, os.ErrNotExist) {
		return map[string]string{}, nil
	}
	if err != nil {
		return nil, err
	}
	m := map[string]string{}
	if err := json.Unmarshal(data, &m); err != nil {
		return nil, fmt.Errorf("decode %s: %w", s.path, err)
	}
	return m, nil
}

func (s *FileStore) save(m map[string]string) error {
	data, err := json.Marshal(m)
	if err != nil {
		return err
	}
	return os.WriteFile(s.path, data, 0o600)
}

// Get implements Store.
func (s *FileStore) Get(k string) (string, error) {
	s.mu.Lock()
	defer s.mu.Unlock()
	m, err := s.load()
	if err != nil {
		return "", err
	}
	v, ok := m[k]
	if !ok {
		return "", ErrNotFound
	}
	return v, nil
}

// Put implements Store.
func (s *FileStore) Put(k, v string) error {
	s.mu.Lock()
	defer s.mu.Unlock()
	m, err := s.load()
	if err != nil {
		return err
	}
	m[k] = v
	return s.save(m)
}

// Delete implements Store.
func (s *FileStore) Delete(k string) error {
	s.mu.Lock()
	defer s.mu.Unlock()
	m, err := s.load()
	if err != nil {
		return err
	}
	delete(m, k)
	return s.save(m)
}

// Keys implements Store and returns the keys sorted.
func (s *FileStore) Keys() ([]string, error) {
	s.mu.Lock()
	defer s.mu.Unlock()
	m, err := s.load()
	if err != nil {
		return nil, err
	}
	keys := make([]string, 0, len(m))
	for k := range m {
		keys = append(keys, k)
	}
	sort.Strings(keys)
	return keys, nil
}
go
// Package storetest is a contract test suite for storefake.Store, in the
// style of testing/fstest.TestFS: every implementation, fake or real, calls Run.
package storetest

import (
	"errors"
	"slices"
	"testing"

	"academy/mocking-interfaces-di/storefake"
)

// Run executes the behavioural contract against fresh stores from newStore.
func Run(t *testing.T, newStore func(t *testing.T) storefake.Store) {
	t.Helper()

	t.Run("missing key is ErrNotFound", func(t *testing.T) {
		s := newStore(t)
		if _, err := s.Get("nope"); !errors.Is(err, storefake.ErrNotFound) {
			t.Fatalf("Get(missing) err = %v, want ErrNotFound", err)
		}
	})
	t.Run("put then get", func(t *testing.T) {
		s := newStore(t)
		if err := s.Put("a", "1"); err != nil {
			t.Fatal(err)
		}
		if v, err := s.Get("a"); err != nil || v != "1" {
			t.Fatalf("Get = %q, %v", v, err)
		}
	})
	t.Run("put overwrites", func(t *testing.T) {
		s := newStore(t)
		_ = s.Put("a", "1")
		_ = s.Put("a", "2")
		if v, _ := s.Get("a"); v != "2" {
			t.Fatalf("Get = %q, want 2", v)
		}
	})
	t.Run("delete is idempotent", func(t *testing.T) {
		s := newStore(t)
		_ = s.Put("a", "1")
		for range 2 {
			if err := s.Delete("a"); err != nil {
				t.Fatalf("Delete err = %v", err)
			}
		}
		if _, err := s.Get("a"); !errors.Is(err, storefake.ErrNotFound) {
			t.Fatalf("Get after delete err = %v", err)
		}
	})
	t.Run("keys are sorted", func(t *testing.T) {
		s := newStore(t)
		for _, k := range []string{"b", "c", "a"} {
			_ = s.Put(k, k)
		}
		keys, err := s.Keys()
		if err != nil || !slices.Equal(keys, []string{"a", "b", "c"}) {
			t.Fatalf("Keys = %v, %v", keys, err)
		}
	})
}
go
package storefake_test

import (
	"path/filepath"
	"testing"

	"academy/mocking-interfaces-di/storefake"
	"academy/mocking-interfaces-di/storefake/storetest"
)

// The same contract runs against the fake and the durable implementation. If
// the fake ever drifts from the real behaviour, one of the two runs fails.
func TestMemStoreContract(t *testing.T) {
	storetest.Run(t, func(*testing.T) storefake.Store { return storefake.NewMemStore() })
}

func TestFileStoreContract(t *testing.T) {
	storetest.Run(t, func(t *testing.T) storefake.Store {
		return storefake.NewFileStore(filepath.Join(t.TempDir(), "store.json"))
	})
}

Mechanics ​

What a mock library really does Important ​

Every generated mock is a struct with one method per interface method. The method records its arguments, looks up a matching expectation, and returns the programmed values.

Steptestify/mockgomock
Registerm.On("Notify", args...)ctrl.RecordCall(...) via EXPECT()
Callm.Called(args...)ctrl.Call(...)
MatchArguments.DiffMatcher.Matches
No matchPanic with a difft.Fatalf "Unexpected call to ..."
VerifyAssertExpectations(t)Controller.Finish via t.Cleanup

Exact messages worth recognising Must-know ​

SourceTextMeaning
gomockUnexpected call to *gomockdemo.MockLedger.Credit(...) because: there are no expected calls of the method "Credit" for that receiverThe code called something with no EXPECT()
testifyFAIL: 0 out of 1 expectation(s) were met. The code you are testing needs to make 1 more call(s).An On(...) was never consumed
sqlmockExpectationsWereMet returns an error naming the unmet expectationA query you scripted never ran
Gopanic: runtime error: invalid memory address or nil pointer dereferenceUn-faked method on an embedded nil interface
mockgen v0.5.2 on Go 1.27.4invalid array length -delta * delta in x/tools/internal/tokeninternalGenerator pins an old x/tools; use v0.6.0

Real outputs behind the tables Good to know ​

The gomock and testify failure texts above were produced by deliberately incomplete tests in a scratch copy of the module. The race detector was on for every run of the snippet module (go test -race -count=1 ./...). go vet and gofmt -l . are clean.

Solving the classic problems ​

ProblemSolutionHowAdvantageCost / limitation
Code calls time.NowInject a clockClock interface or now func()Exact assertionsOne parameter
Code calls the networkInject a client or gatewayhttptest, fake RoundTripperFast, forced failuresFake may drift
Code uses a global DBPass the repositoryConstructor injectionParallel testsRoot must wire it
Test needs one failure modeStub with an errorstubGateway{err: ErrDeclined}TrivialNone
Interface too wide to fakeSplit it, or embedInterface embeddingSmaller doublesReview boundary
Interaction is the requirementMockgomock InOrder, testify NotBefore/OnceOrder and count checkedBrittle
Fake drifts from realContract teststoretest.RunHonest fakeOne suite per interface
Wiring growswire or fxProvidersLess boilerplateTool to learn
Hidden dependencyConstructor parameterRemove the globalVisibleRewrite

Replace a global with a constructor parameter ​

Take before.Checkout: move PaymentURL, the map and the clock into a struct, make them constructor parameters (or options), keep func main as the only caller of the concrete constructors. The test shrinks from "patch, restore, clear" to "build, call, assert" and gains t.Parallel().

Make errors injectable ​

Add a field to a stub for every failure the code should survive (err error). Table-driven tests (Testing & Benchmarking) then cover declined, disk full and timeout in one loop. Use errors.Is in the assertion (Errors, Panic, Recover & Defer).

Test goroutines with injected ctx ​

Pass t.Context() (Go 1.24: "canceled after the test completes and before test cleanup functions run") into the code under test so background work stops with the test. See context.

Choosing ​

How to choose: real, fake, generated mock, and when to add wire or fxNeed to isolate a dependency?(network, clock, disk, DB)Cheap and deterministic?use the real thing(pure code, t.TempDir, bytes.Buffer)Stdlib has a fake?httptest, iotest, fstest, strings.ReaderOwn interface neededsmall, consumer-defined1-3 methodsBehaviour mattershand-written fake or stub+ contract test if sharedInteraction matters(was it called, how often, order)spy, or generated mockMany methods or many testsmockery (testify/mock)or mockgen (gomock)Wiring: manual firsta Build function in the composition rootfine up to dozens of constructorsAdd wire or fx whenthe graph is large and shared by many binarieswire: compile time; fx: runtime + lifecycle
SituationRecommended doubleExtra techniqueReason
Pure computationNone: call itTable-driven testNo dependency
Needs input bytesstrings.Readeriotest faultsStdlib fakes
Time-dependentFake clocksynctest for goroutines (1.25)Deterministic
Outgoing HTTPhttptest.NewServer or fake transportContract with sandbox occasionallyReal wire format
Repository callersIn-memory fakeContract testBehaviour over interaction
Repository mapping codesqlmockA few real-DB testsCheap error paths
SQL correctness, migrationsReal database (testcontainers named)CI serviceOnly the engine knows
"Must call X once, then Y"gomock or testify mockInOrder, NotBefore, OnceInteraction is the spec
Wide third-party interfaceEmbedded-interface partial fakeNarrow interface at your boundarySmall doubles
Many binaries, big graphwireCI check of wire_gen.goCompile-time checking
Many components with lifecyclefxfx.ValidateApp in testsOrdered start and stop

In architecture: from a single process to a distributed system ​

Monolith: one process, one database ​

One binary, one main, one composition root. Each package declares the small interfaces it needs; Build constructs the pool, repositories, services and handlers; unit tests inject fakes, a handful of integration tests run Build against a real database. The simplest correct monolith has no DI framework and no generated mocks beyond the few interaction-heavy spots.

Modular monolith and multiple databases ​

Module boundaries become interfaces: billing exposes a struct, orders declares type Biller interface { Charge(...) } and receives it from the root. Each module owns its store interface, so a second database (sessions in Redis) is one more constructor argument, not a change to every caller. Shared fakes live in a modulename/modtest package and are covered by contract tests.

Microservices ​

Across a network, the injected thing is a client: PaymentGateway is satisfied by an HTTP or gRPC client in production and by a stub in unit tests. The consumer's interface models the use case (Charge), not the wire protocol, so the transport can change. Test the client against httptest for the HTTP mapping, against a fake in the consumer's tests, and add a consumer-driven contract (the provider's team runs the consumer's expectations) when two teams own the two sides. See A REST API in Go and Middlewares.

Distributed data: replicas, caches, sharded databases, multi-region ​

Fakes are single-copy and instantly consistent, so they cannot reproduce replica lag, cache staleness or partial failure. Inject a ReadStore and a WriteStore separately so a test can make the read side return stale data; script failures with a stub (err on the second call); and treat a fake as a model of the contract you rely on, not of the infrastructure. Concurrency and timing bugs need the real thing under -race and, for fakes with state, a mutex like MemStore has.

Scaling path: 1×, 10×, 100× ​

Load / team sizeWhat changesTestability practice
1× (one developer, one service)A few interfaces, hand-written doublesConstructor injection, Build in main
10× (several packages, a team)Repeated doubles, drifting fakesShared fakes + contract tests, mockery or mockgen for wide interfaces
100× (many services, many teams)Big graphs, lifecycle ordering, cross-team contractswire or fx, ValidateApp/wire in CI, consumer-driven contracts, a real-database integration tier

Lab ​

All commands run from docs/snippets/go/mocking-interfaces-di/go with export PATH=/opt/homebrew/bin:$PATH. Labs 1 to 4 were run on Go 1.27.4; labs 5 and 6 are expected, not run.

1. Run everything with the race detector (real) ​

$ gofmt -l .
$ go vet ./...
$ go test -race -count=1 ./...
ok  	academy/mocking-interfaces-di/after
ok  	academy/mocking-interfaces-di/antipatterns
ok  	academy/mocking-interfaces-di/before
ok  	academy/mocking-interfaces-di/clockinject
ok  	academy/mocking-interfaces-di/cmd/server
ok  	academy/mocking-interfaces-di/doubles
ok  	academy/mocking-interfaces-di/fxapp
ok  	academy/mocking-interfaces-di/gomockdemo
ok  	academy/mocking-interfaces-di/ifacepitfalls
ok  	academy/mocking-interfaces-di/mockerydemo
ok  	academy/mocking-interfaces-di/readerfake
ok  	academy/mocking-interfaces-di/sqlrepo
ok  	academy/mocking-interfaces-di/storefake
ok  	academy/mocking-interfaces-di/testifymock
ok  	academy/mocking-interfaces-di/wiredi
ok  	academy/mocking-interfaces-di/wiring

2. Make gomock fail (real) ​

Copy the module, delete the Credit expectation in TestTransferHappyPathInOrder and run it:

--- FAIL: TestMissingCredit (0.00s)
    ledger.go:34: Unexpected call to *gomockdemo.MockLedger.Credit([context.Background.WithCancel b 300]) ... because: there are no expected calls of the method "Credit" for that receiver
FAIL

3. Make testify fail (real) ​

Register On("Notify", ...).Once() and never call it, then AssertExpectations(t):

--- FAIL: TestForgotToCall (0.00s)
    FAIL:	Notify(string,string,string)
    FAIL: 0 out of 1 expectation(s) were met.
        	The code you are testing needs to make 1 more call(s).

4. Regenerate the generated files (real) ​

$ (cd gomockdemo && go run go.uber.org/mock/mockgen@v0.6.0 -source=ledger.go -destination=mock_ledger_test.go -package=gomockdemo)
$ (cd mockerydemo && go generate ./...)      # mockery v2.53.8, prints a v3 packages-config deprecation warning
$ (cd wiredi && wire)                        # wire CLI v0.7.0 built outside the module

5. Break the typed-nil rule (expected, not run) ​

Change ValidateFixed to var ve *ValidationError; return ve and run go test ./ifacepitfalls. Expected: the final assertions of TestTypedNilIsNotNilInterface fail, because the "fixed" function now returns a non-nil error even for a valid name.

6. Add a PostgreSQL contract run (expected, not run) ​

Implement storefake.Store over a kv(key text primary key, value text) table in PostgreSQL started by testcontainers and call storetest.Run on it; expect the same five subtests to pass, and any divergence (for example Keys returning unsorted rows without ORDER BY key) to fail "keys are sorted".

For PHP/Laravel developers ​

Laravel container comparison (bind, singleton, Mockery, fakes): Laravel has the same idea with a container that does the wiring at run time. The Laravel docs say: "if you write a class that implements an interface and you wish to type-hint that interface on a route or class constructor, you must tell the container how to resolve that interface", which is bind. singleton resolves "one time", and instance registers an existing object. For tests the docs say mocking helpers "primarily provide a convenience layer over Mockery", and facades make static-looking calls swappable: "One of the primary benefits of dependency injection is the ability to swap implementations of the injected class." In Go there is no container: the composition root is ordinary code, and the "binding" is a constructor argument.

php
// Laravel: bind an interface in a service provider, then replace it in a test.
$this->app->bind(PaymentGateway::class, StripeGateway::class);          // provider
$this->app->singleton(Clock::class, fn () => new SystemClock());         // one instance

$this->mock(PaymentGateway::class, function (MockInterface $mock) {      // Mockery
    $mock->shouldReceive('charge')->once()->andReturn('pay-1');
});
Http::fake(['payments.example.test/*' => Http::response(['id' => 'pay-77'], 200)]);
Event::fake();                                                           // built-in fakes
Laravel / PHPGo
$this->app->bind(Iface::class, Impl::class)Constructor argument in Build, wire.Bind or fx.As
$this->app->singleton(...)One instance created in the root and shared
Type-hinted constructor autowiringExplicit parameters; wire/fx for automation
$this->mock(...), Mockery::mockHand-written stub/spy, testify/mock, gomock
partialMock, spyEmbedded-interface partial fake, hand-written spy
Http::fake, Event::fake, Queue::fakehttptest, fake RoundTripper, fake gateway
Cache::shouldReceive (facade mock)Inject a Cache interface
$this->travel(5)->seconds()Fake clock or synctest
Facade (static proxy)Do not use globals: inject

Common misconceptions ​

BeliefReality
Every struct needs an interfaceOnly dependencies a consumer wants to replace; return concrete types
The interface goes next to the implementationThe consumer declares it
Mocks and fakes are the sameDifferent doubles: mocks verify calls, fakes behave
sqlmock tests my SQLIt tests that the string you expect is sent; the database never runs it
testify is required in GoThe standard library is enough; TestComments discourages assert libraries
wire is a runtime containerIt is a build-time code generator
fx finds missing dependencies at compile timeAt start-up, or in fx.ValidateApp
sync.Once makes a singleton testableIt only makes initialisation race-free
A nil pointer in an interface is a nil interfaceIt has a type, so it is not nil
golang/mock is currentUse go.uber.org/mock
Sleeping in tests is fine if shortInject a clock
Generated mocks never need reviewCommit them and regenerate in CI

Cheat sheet ​

TopicRemember
Interface placementDeclare it where it is used
Return typesReturn structs, accept interfaces
Size1-3 methods; proverb: bigger interface, weaker abstraction
InjectionConstructor parameters; options for optional ones
Double choiceReal, then stub or fake, then spy, then mock
ClockClock interface or now func() time.Time; synctest in 1.25
IOTake io.Reader/io.Writer; iotest for faults
HTTPhttptest.NewServer or a fake RoundTripper
SQLFake for callers, sqlmock for mapping, real DB for SQL
testifyrequire stops, assert continues, AssertExpectations
gomockgo.uber.org/mock, NewController(t), InOrder
mockeryNewMockX(t), EXPECT(), commit generated files
WiringOne composition root; run(ctx, getenv) from main
wire / fxwire = build-time, fx = runtime and lifecycle
AvoidGlobals, init() side effects, service locators
Typed nilReturn literal nil, not a nil pointer variable

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — Who should declare the interface a function takes, and what should the implementing package return? Must-know ​

Answer

Answer: The consuming package declares it, small and with only the methods it calls; the implementing package exports and returns a concrete struct. This keeps new methods non-breaking and avoids interface pollution.

2 — What is the difference between a stub, a spy, a fake and a mock? Must-know ​

Answer

Answer: A stub returns canned answers; a spy is a stub that records calls for later assertions; a fake has working logic with a shortcut (an in-memory store); a mock holds expectations and fails the test itself when they are not met. See Test doubles.

3 — How do you test code that depends on time.Now()? Must-know ​

Answer

Answer: Inject the clock, as a Clock interface or a now func() time.Time, and advance a fake by hand. Avoid time.Sleep. For goroutines with timers, testing/synctest (generally available in Go 1.25) virtualises time. See Mocking the clock.

4 — Why can err != nil be true when a function "returns nil"? Important ​

Answer

Answer: The function returned a nil pointer of a concrete type as an error, which is the pair (type, nil), not a nil interface. Return the literal nil on success. See Nil interface vs typed nil.

5 — What does sqlmock prove and what does it not? Important ​

Answer

Answer: It proves your code sends the SQL and arguments you scripted and maps results and errors correctly. It cannot prove the SQL is valid or fast, because no database runs. Use a real database for that. See Database fakes vs sqlmock vs a real database.

6 — Why does Go culture warn against defining interfaces "for mocking"? Must-know ​

Answer

Answer: The Code Review Comments say to design the API so it can be tested through the real implementation's public API, and to define interfaces only once there is a consumer. A producer-side interface hides new methods and forces mock regeneration.

7 — What is a composition root and where is it in a Go program? Must-know ​

Answer

Answer: The one place that constructs concrete types and wires the dependency graph, normally main or a Build function it calls. Everything else sees interfaces. See Manual DI.

8 — When would you choose wire over fx, and when neither? Important ​

Answer

Answer: wire for big graphs where you want compile-time errors and no runtime reflection; fx when ordered start and stop hooks matter; neither when a hand-written Build of a few dozen lines is clear.

9 — What is wrong with a package-level variable assigned in init() as a dependency? Must-know ​

Answer

Answer: It hides the dependency from signatures, runs on import, cannot be replaced without mutating shared state, and blocks parallel tests. See Globals, init() and singletons.

10 — How do you keep an in-memory fake honest? Important ​

Answer

Answer: Write a contract test suite and run it against the fake and every real implementation, as storetest.Run does. See Contract tests.

11 — Why use testify's require for setup errors and assert for value checks? Good to know ​

Answer

Answer: require calls FailNow, so later lines do not panic on a nil result; assert records and continues so you see all mismatches. The Go wiki still advises that plain testing suffices. See testify.

12 — How does a service locator differ from dependency injection in failure behaviour? Good to know ​

Answer

Answer: A locator fails at run time when Get is called with a missing or wrongly typed service; constructor injection fails at compile time because the argument is required. See Service locator.

Glossary ​

TermMeaning
InterfaceSet of method signatures; satisfied implicitly
Small interfaceOne to three methods; easy to fake
Accept interfaces, return structsParameters are interfaces, return values concrete types
Consumer-defined interfaceInterface declared in the package that uses it
Interface pollutionInterfaces nobody needs, usually declared "for mocking"
Dependency injectionHanding a thing its collaborators instead of letting it build them
Constructor injectionDependencies as NewX parameters
Functional options...Option arguments (WithClock) that tweak defaults
Test doubleAny replacement of a production object in a test
DummyDouble that fills a parameter and is never used
StubDouble with canned answers
SpyStub that records how it was called
FakeWorking but simplified implementation
MockDouble with pre-programmed expectations that verifies itself
Hand-written fakesDoubles you write yourself in test files
Test seamA place where behaviour can be replaced without editing the code
testify/mocktestify package for expectation-based doubles (On, Return, AssertExpectations)
mockeryGenerator of testify/mock doubles
gomock / uber-go/mockExpectation-based mock library with mockgen generator (go.uber.org/mock)
mockgengomock's generator (archive, source, package modes)
Mocking the clockInjecting time so tests control "now"
httptestStandard library fakes for HTTP servers and handlers
iotestStandard library readers that inject faults
sqlmockFake database/sql driver for scripted queries
testcontainersLibrary that starts containers for integration tests (named only)
Interface embeddingComposing interfaces, or embedding an interface in a struct for partial fakes
Typed nilNil pointer stored in an interface: the interface is not nil
Dependency graphConstructors and their parameters as a directed graph
Composition rootThe single place where the graph is built
package main wiringmain reads config, calls the root, owns process concerns
wireGoogle's build-time DI code generator
Provider / injectorwire terms: a constructor function / a generated entry point
fxUber's runtime DI and lifecycle framework
Manual DIWriting the wiring by hand
Globals and init()Package-level state set at import; hurts testability
SingletonProcess-wide single instance, state leaks between tests
Service locatorRegistry asked for dependencies by name inside code
Contract testOne suite every implementation of an interface must pass
Golden fakeA fake shipped with production code and held to the contract
Container (Laravel)Run-time resolver with bind, singleton, instance
Mockery (PHP)PHP mocking library behind Laravel's mock helpers

References ​

Built by Morteza Negahi