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
- Writing Unit Tests with testing
- Table-Driven Tests
- Test Doubles: Mocks and Stubs
- Test Coverage and testify