Moq generates a mock struct from any Go interface for use in tests. It integrates with go generate to avoid handwritten mock boilerplate.
Overview
Moq is a code generation tool for Go that builds a struct implementing a chosen interface. Each interface method becomes a function field on the mock, and generated methods delegate to those fields so tests can supply per-call behavior inline.
You invoke it from the command line or via a //go:generate directive above the interface definition, pointing at the package directory and output file. After go generate, tests use the mock type with custom Func fields, and can inspect or reset recorded calls through generated helpers.
The pattern keeps mock logic inside the test that needs it instead of maintaining large shared mock types. Moq panics if a nil function field is called, encouraging explicit setup. Naming arguments in the interface improves generated signatures.
Install the latest release with go install, requiring a recent Go toolchain for builds from source. Older Go versions can use release binaries. A -fmt noop flag helps debug when generated code fails go/format validation.
Key features
- Mock structs from Go interfaces
- go generate workflow integration
- Per-method function fields for behavior
- Method call tracking and reset helpers
- Command-line and directive invocation
- Panic on uncalled nil mock methods
- Debug mode without go/format
- MIT-licensed standalone binary
Use cases
- Unit tests with swappable dependencies
- Inline mock behavior per test case
- Reducing handwritten mock structs
- Testing packages that depend on interfaces
- CI pipelines using go generate