MockGen vs Handwritten Mocks: When to Automate Mock Generation
Short verdict
- Automate with MockGen when interfaces are numerous, large, or require precise interaction verification.
- Handwrite fakes when interfaces are small, behavior is simple, or you want explicit, idiomatic test code without code generation.
When to choose MockGen (automate)
- Large/complex interfaces: Saves substantial boilerplate for many methods.
- Detailed interaction assertions: Need ordered calls, call counts, argument matchers, or strict expectation checks.
- Consistent, repeatable mocks: Team-wide standardization and CI-friendly generation.
- Faster iteration on tests: Regenerate mocks after interface changes instead of editing hand-written code.
- Tooling exists in your workflow: You accept generated files or use go:generate and keep mocks as _test or separate package files.
When to handwrite mocks (do not automate)
- Tiny, single-method interfaces: Writing a small fake is quicker and clearer.
- Highly custom behavior: Tests need bespoke logic, stateful scenarios, or complex side effects that are simpler to express by hand.
- Avoiding code generation: Policy or preference to keep repository free of generated code or extra tooling.
- To prevent coupling/complexity: Handwritten fakes can be simpler to reason about and debug.
- To avoid package/cyclic dependency issues: Placing minimal fakes in tests can sidestep generation placement problems.
Practical guidelines (decision checklist)
- If you have >3 interfaces or interfaces with >4 methods — prefer MockGen.
- If tests require verifying call order, counts, or argument matchers — prefer MockGen.
- If a fake needs complex, stateful, scenario-specific behavior — handwrite it.
- If your CI/build process prohibits codegen or your team dislikes generated files in VCS — handwrite or keep generated mocks out of repo.
- If cyclic dependencies appear when placing generated mocks, prefer test-only hand-written fakes or adjust package placement with care.
Tips for using both
- Keep simple fakes hand-written and use MockGen for the rest.
- Generate mocks into_test.go files or a mocks package to avoid production-package pollution.
- Add go:generate lines so team members can regenerate easily.
- Treat generated mocks as disposable: prefer regenerating over manual edits.
Sources: gomock/mockgen community guides and Go testing best-practice articles.
Leave a Reply