Overview of mockery
v3stretchr/testify/mock package to eliminate the boilerplate code typically required when writing mocks for unit tests.repository·v3·Indexed 27 days ago
https://github.com/vektra/mockeryA high-performance code generation tool for Go that creates mock implementations of interfaces using the testify/mock framework. It features centralized YAML configuration via .mockery.yml, support for custom Go templates, and the ability to use //mockery:generate directives in source code to reduce manual boilerplate in unit tests.
stretchr/testify/mock package to eliminate the boilerplate code typically required when writing mocks for unit tests.Mockery is a high-performance code-generation framework for Go. Key features include:
moq..mockery.yaml file instead of scattered //go:generate comments.Mockery provides a migration tool to convert v2 configuration files to the v3 schema on a best-effort basis.
Run the command pointing to your existing v2 YAML configuration. The tool will generate a new .mockery_v3.yml file and output a deprecation table in the terminal highlighting manual interventions required (such as changes to replace-type schema or template variable renames).
Note: This tool is not comprehensive and may miss edge cases.
$ mockery migrate --config ./.mockery_v2.ymlYou can install mockery using go install.
Warning: Do not use @latest as this will pull from the latest, potentially untagged, commit on the master branch. Instead, specify a version tag.
To generate mocks for external packages, first ensure the package is available in your project using go get. Then, include the external package path in your mockery configuration.
Example configuration for a Temporal SDK package:
packages:
go.temporal.io/sdk:
config:
all: true
recursive: true
dir: mocks/{{.SrcPackagePath}}
filename: mocks.goThe #!yaml inpackage: parameter allows you to override mockery's automatic detection of whether a generated mock file resides inside or outside the original interface's package.
By default, if mockery detects the mock is outside the original package, it adds import statements and uses qualified type names (e.g., pkg.TypeName). Setting #!yaml inpackage: true forces mockery to treat the mock as being inside the same package, which removes the extra import and uses the unqualified type name (e.g., TypeName).
#!yaml inpackage: trueYou can pull the mockery image from Docker Hub and run it to generate mocks for your project by mounting your current directory.
docker pull vektra/mockery
# Generate all mocks for your project
docker run -v "$PWD":/src -w /src vektra/mockery:3Mockery generates constructor functions (e.g., NewMockRequester(t)) that simplify test setup. These constructors automatically:
AssertExpectations to be called via t.Cleanup() at the end of the test.testing.TB interface on the mock.Mock object to prevent panics when unexpected calls occur.func TestRequesterMock(t *testing.T) {
m := NewMockRequester(t)
m.EXPECT().Get("foo").Return("bar", nil).Once()
retString, err := m.Get("foo")
assert.NoError(t, err)
assert.Equal(t, retString, "bar")
}When upgrading to Mockery v3, several configuration parameters have changed or been removed. Use the following mapping to update your configuration:
| v2 Parameter | v3 Status / Change |
|---|---|
inpackage | Removed. Mockery now automatically detects if a mock is in the same package. |
keeptree | Removed. This parameter is no longer used. |
with-expecter | Removed. testify-style mocks now always generate expecter methods. |
exclude | Renamed to exclude-subpkg-regex. |
unroll-variadic | Moved. Now must be passed under the template-data map. |
resolve-type-alias | Changed. Now defaults to False (was True in v2). |
replace-type | Updated. The schema is now more explicit compared to the v2 string list format. |
Instead of using a central configuration file, you can use the //mockery:generate directive within Go doc comments to control mock generation for specific interfaces. This allows you to override configuration directly at the source of the interface.
To enable generation for a specific interface, add //mockery:generate: true to its doc comments. If you have set all: false in your .mockery.yml configuration, this directive will opt that specific interface into the generation process.
// Requester is an interface that defines a method for making HTTP requests.
//
//mockery:generate: true
type Requester interface {
Get(path string) (string, error)
}Mockery automates the creation of mock implementations for Golang interfaces. It inspects your source code and generates implementations that allow you to define behavior (expectations) during testing.
To generate mocks, you can use a .mockery.yaml configuration file to specify the packages and interfaces you want to mock. This is preferred over using multiple //go:generate commands as it provides a centralized and flexible configuration scheme.
packages:
github.com/org/repo:
interfaces:
DB:The replace-type configuration parameter in .mockery.yml allows you to substitute a specific type in a generated mock with a different type. This is particularly useful when you need to work around packages that use internal types that are not accessible or desired in your test environment.
To use this, define a mapping in your .mockery.yml where the key is the full package path of the type you want to replace, and the value is a map containing the specific type name and its replacement details (pkg-path and type-name).