0PricingLogin
Go Academy · Lesson

Test Doubles: Mocks and Stubs

Interfaces for testability and dependency injection

Test doubles overview

A test double replaces a real dependency in tests. Types: stub (returns canned responses), mock (verifies interactions), spy (records calls), fake (working in-memory impl).

Interfaces enable test doubles

Design functions to accept interfaces rather than concrete types. In production, pass the real implementation; in tests, pass a test double.

type UserStore interface {
    FindByID(id int) (*User, error)
}

func GetUser(store UserStore, id int) (*User, error) {
    return store.FindByID(id)
}

All lessons in this course

  1. Writing Unit Tests with testing
  2. Table-Driven Tests
  3. Test Doubles: Mocks and Stubs
  4. Test Coverage and testify
← Back to Go Academy