Introduction
Mockery reads Go interface definitions and generates mock structs that implement those interfaces using testify/mock. This eliminates the tedious work of hand-writing mocks and keeps them in sync with interface changes through code generation.
What Mockery Does
- Parses Go source code to discover interface definitions
- Generates mock implementations backed by testify/mock
- Supports config-driven generation via
.mockery.yamlfor entire projects - Handles generics, embedded interfaces, and vendor dependencies
- Integrates with
go generatefor automated regeneration
Architecture Overview
Mockery uses Go's packages.Load to parse source files and extract interface declarations. For each matched interface, it walks the method set, resolves all parameter and return types (including generics), and emits a Go source file containing a struct with On/Return/Call methods from testify/mock. The generated code is deterministic, enabling clean diffs on regeneration.
Setup & Configuration
- Install globally with
go install github.com/vektra/mockery/v2@latest - Create
.mockery.yamlat the project root to configure packages and output paths - Run
mockerywith no flags to process all configured interfaces - Add
//go:generate mockerycomments for per-file generation - Use
--inpackageto place mocks alongside the interface source file
Key Features
- Config file support for multi-package projects with pattern matching
- Generates mocks for generic interfaces with type parameter resolution
- Supports multiple output formats: per-interface files, single file, or in-package
- Automatic cleanup of stale mock files when interfaces are removed
- Generates constructor functions like
NewMockX(t)that auto-register cleanup
Comparison with Similar Tools
- gomock (uber-go/mock) — Google-originated framework with its own mock API instead of testify/mock
- moq — generates simple stub implementations without a mock framework dependency
- counterfeiter — produces fakes with call tracking; popular in Cloud Foundry projects
- Hand-written mocks — no dependency but tedious to maintain and easy to drift from the interface
FAQ
Q: Does Mockery support Go generics? A: Yes. Mockery v2.20+ generates mocks for generic interfaces with correct type parameters.
Q: How do I regenerate all mocks at once?
A: Define your interfaces in .mockery.yaml and run mockery from the project root. All configured mocks regenerate in one pass.
Q: Can I use Mockery without testify?
A: No. Generated mocks depend on github.com/stretchr/testify/mock. If you want framework-free mocks, consider moq.
Q: How do I mock an interface from an external package?
A: Add the external package path to .mockery.yaml under the packages key and run mockery normally.