MockGen: A Beginner’s Guide to Generating Go Mocks
What MockGen is
MockGen is a tool from the Go ecosystem (part of the gomock project) that generates mock implementations of Go interfaces. These mocks let you isolate units under test by replacing real dependencies with controllable, observable fakes.
Why use MockGen
- Isolation: Test code that depends on interfaces without invoking real implementations (databases, networks, etc.).
- Behavior verification: Assert that functions call dependencies with expected arguments and sequence.
- Repeatability: Replace flaky external systems with deterministic mocks.
- Speed: Tests run faster when heavy operations are mocked.
Installation
Install gomock and mockgen with:
Code
go install github.com/golang/mock/mockgen@latest go get github.com/golang/mock/gomock
This installs the mockgen binary in your GOPATH/bin or Go bin directory.
Basic usage patterns
- Generate mocks from a package and interface name:
Code
mockgen> mock_package/mockinterface.go
Example:
Code
mockgen github.com/example/project/service Authenticator > mocks/mockauthenticator.go
- Generate mocks from source files (when interfaces are local):
Code
mockgen -source=path/to/file.go -destination=mocks/mockfile.go -package=mocks
- Generate multiple interfaces at once by listing them or using package-level generation.
Typical test setup
- Create a gomock Controller in your test:
Code
ctrl := gomock.NewController(t) defer ctrl.Finish()
- Create the mock:
Code
mockAuth := mocks.NewMockAuthenticator(ctrl)
- Set expectations:
Code
mockAuth.EXPECT().Login(“user”,“pass”).Return(true, nil)
- Inject mock into the system under test and run assertions.
Common patterns and tips
- Use table-driven tests and set expectations per subtest to keep tests clear.
- Use gomock.InOrder(…) to enforce call order when needed.
- Use gomock.Any(), gomock.Eq(), gomock.AssignableToTypeOf() for flexible matching.
- Keep mocks in a separate package (mocks) to avoid import cycles and to test interface boundaries.
- Regenerate mocks when interfaces change; consider adding mockgen invocation to build scripts or Makefile.
When not to mock
- Don’t mock value types or simple structs — focus on external dependencies and behaviors.
- Prefer small, well-defined interfaces; large interfaces are harder to mock and maintain.
Example workflow (concise)
- Define an interface in your package.
- Run mockgen to produce mock code in a mocks package.
- In tests, create gomock.Controller, instantiate mock, set EXPECT calls, run test, verify.
References for further reading
- gomock README and mockgen usage (search repository: github.com/golang/mock)
- Examples in open-source Go projects for real-world patterns
Leave a Reply