Introduction
GoMock (now maintained by Uber as go.uber.org/mock) generates mock implementations of Go interfaces from source code or reflection. It provides an expectation API for verifying call arguments, ordering, and return values in unit tests.
What GoMock Does
- Generates type-safe mock structs from Go interface definitions
- Provides EXPECT() API for setting call expectations and return values
- Supports argument matching with built-in and custom matchers
- Verifies expected call counts and ordering constraints
- Integrates with Go's standard testing.T for failure reporting
Architecture Overview
The mockgen tool parses Go source files or uses reflection to extract interface method signatures, then generates mock struct code with EXPECT() recorder methods. At runtime, the gomock.Controller tracks expectations and verifies them against actual calls. Unmet or unexpected calls trigger test failures through the testing.T interface.
Self-Hosting & Configuration
- Install mockgen via go install go.uber.org/mock/mockgen@latest
- Generate mocks with -source (file mode) or -destination (reflect mode)
- Place generated mocks in a mocks/ package by convention
- Create a gomock.Controller in each test function with gomock.NewController(t)
- Use go:generate comments to automate mock regeneration
Key Features
- Type-safe generated code: compile-time errors for interface changes
- Flexible argument matchers: Eq, Any, Nil, and custom Matcher interface
- InOrder() helper for enforcing call sequence constraints
- DoAndReturn for executing custom logic when a mock is called
- Active maintenance under Uber's go.uber.org/mock module
Comparison with Similar Tools
- testify/mock — Runtime reflection-based; GoMock is code-generated and type-safe
- counterfeiter — Generates fakes with similar approach; GoMock has a richer expectation API
- moq — Generates simple mock structs; GoMock adds call verification and ordering
- mockery — Generates testify-compatible mocks; GoMock uses its own controller pattern
- gomock (golang/mock) — The original; uber-go/mock is the actively maintained fork
FAQ
Q: What happened to golang/mock? A: The original Google repository was archived. Uber forked it as go.uber.org/mock and continues active development.
Q: Source mode vs reflect mode — which should I use? A: Source mode (-source) is simpler and works without building. Reflect mode handles interfaces from external packages.
Q: Can I mock functions, not just interfaces? A: GoMock requires interfaces. Wrap functions in an interface to make them mockable.
Q: How do I verify a method was NOT called? A: Set EXPECT().Times(0) on the method to assert it is never invoked.