GoMock
Mocking framework for Go that generates mock implementations from interfaces for unit tests.
Official Documentation ↗uber-go/mock v0.4 / Go 1.20+. Check the official docs for the latest API surface.Installation
go get go.uber.org/mockMethods
No methods match this filter.
Overview
GoMock generates mock implementations of interfaces so unit tests can replace collaborators and assert interactions. It works with any test framework through a controller.
Core Methods
Generate mocks with mockgen, create a controller per test, set expectations with EXPECT, and call Finish to verify them. Matchers control argument matching.
Usage Notes
Mock at the boundary of the unit under test, keep expectations minimal, and always call Finish. Prefer fakes for rich behavior and mocks for verifying calls.
Common Pitfalls
Over-specified expectations make tests brittle and break on refactors. Forgetting Finish hides missed calls. Mocking concrete types is impossible; only interfaces can be mocked.
FAQ
- How are mocks generated?
- Run mockgen against an interface with either source mode or reflect mode to generate a mock type in a package, then instantiate it with a controller.
- What does ctrl.Finish verify?
- It asserts that all expected calls occurred the required number of times. Without it, unsatisfied expectations go unnoticed.
- Should I mock or use a fake?
- Mocks are convenient for verifying interactions but can couple tests to implementation. For complex behavior, a hand-written fake implementing the interface is often more robust.
Report a problem with this API docOpens a pre-filled issue on GitHub.