The style of mock to be generated is specified using the template parameter.
An output file may contain multiple mocks, but the only rule is that all the mocks in the file must come from the same package. Because of this, mocks for different packages must go in different files.
Additionally, this issue only happens when compiling mockery from source, such as with go install. Our docs recommend not to use go install as the success of your build depends on the compatibility of your Go version with the semantics in use. You would not encounter this issue if using one of the installation methods that install pre-built binaries, like downloading the .tar.gz binaries, or through brew install.
There might be instances where you want a mock to return different values on successive calls that provide the same arguments. For example, we might want to test this behavior:
-
Go
// Return "foo" on the first call
-getter:=NewGetter()
-assert(t,"foo",getter.Get("key"))
-
-// Return "bar" on the second call
-assert(t,"bar",getter.Get("key"))
-
-
This can be done by using the .Once() method on the mock call expectation:
The versioning in this project applies only to the behavior of the mockery binary itself. This project explicitly does not promise a stable internal API, but rather a stable executable. The versioning applies to the following:
-
-
CLI arguments.
-
Parsing of Go code. New features in the Go language will be supported in a backwards-compatible manner, except during major version bumps.
-
Behavior of mock objects. Mock objects can be considered to be part of the public API.
-
Behavior of mockery given a set of arguments.
-
-
What the version does not track:
+
The mockery project follows the standard Semantic Versioning Semantics. The versioning applies to the following areas:
-
The interfaces, objects, methods etc. in the vektra/mockery package.
-
Compatibility of go get-ing mockery with new or old versions of Go.
+
The shape of mocks generated by pre-curated templates.
+
Functions and data provided to templates specified with template:"file://".
+
Configuration options.
+
Mockery is not meant to be used as an imported library. Importing mockery code in external modules is not supported.
When your interfaces are in the main package, you should supply the --inpackage flag.
This will generate mocks in the same package as the target code, avoiding import issues.
Mockery v3 is currently in alpha and should not be used for production.
Mockery is a project that creates mock implementations of Golang interfaces. It inspects source code and generates implementations of the interface that aid in testing.
In addition to providing a number of different styles of mocks, mockery also allows users to provide their own template files that will then be rendered using a set of template data, methods, and functions that provide comprehensive typing information about the Go interface in question.
"},{"location":"#why-use-mockery","title":"Why use mockery?","text":"
You gain access to a number of pre-curated mock implementations that can be used in testing. This includes traditional \"mockery-style\" mocks, as well as other styles from the open source community such as from https://github.com/matryer/moq. Such mocks allow you to quickly define how the implementation should behave under test without having to manually curate your own mocks/stubs/fakes.
Mockery benefits from a large number of performance improvements that almost all other Go code-generation projects currently have not employed. This means that it's orders of magnitude faster for large codebases.
Mockery provides a comprehensive, centralized, flexible, and simple configuration scheme driven off of yaml instead of relying on sprawling //go:generate commands.
Mockery is a code-generation framework. While its original goal is to provide mock implementations for testing purposes, users can supply their own templates to auto-generate any kind of code that needs to be based off of interfaces.
A number of high profile companies, projects, and communities trust Mockery.
All configuration is specified in a .mockery.yml file. An example config file may look like this:
YAML
all: False\ntemplate-data:\n boilerplate-file: ./path/to/boilerplate.txt\ntemplate: mockery\npackages:\n github.com/vektra/example:\n config:\n # Make use of the template variables to place the mock in the same\n # directory as the original interface.\n dir: \"{{.InterfaceDir}}\"\n filename: \"mocks_test.go\"\n outpkg: \"{{.PackageName}}_test\"\n mockname: \"Mock{{.InterfaceName}}\"\n interfaces:\n Foo:\n Bar:\n config:\n # Make it unexported instead\n mockname: \"mock{{.InterfaceName}}\"\n Baz:\n # Create two mock implementations of Baz with different names.\n configs:\n - filename: \"mocks_baz_one_test.go\"\n mockname: \"MockBazOne\"\n - filename: \"mocks_baz_two_test.go\"\n mockname: \"MockBazTwo\"\n io:\n config:\n dir: path/to/io/mocks\n filename: \"mocks_io.go\"\n
These are the highlights of the config scheme:
The parameters are merged hierarchically
There are a number of template variables available to generalize config values.
The style of mock to be generated is specified using the template parameter.
An output file may contain multiple mocks, but the only rule is that all the mocks in the file must come from the same package. Because of this, mocks for different packages must go in different files.
"},{"location":"configuration/#parameter-descriptions","title":"Parameter Descriptions","text":"name templated default description allfalse Generate all interfaces for the specified packages. _anchors{} Unused by mockery, but allowed in the config schema so that you may define arbitrary yaml anchors. config\"\" Set the location of the mockery config file. dir\"mocks/{{.SrcPackagePath}}\" The directory where the mock file will be outputted to. exclude-subpkg-regex[] A list of regular expressions that denote which subpackages should be excluded when recursive: trueexclude-regex\"\" When set along with include-regex, then interfaces which match include-regex but also match exclude-regex will not be generated. If all is set, or if include-regex is not set, then exclude-regex has no effect. filename\"mock_{{.InterfaceName}}.go\" The name of the file the mock will reside in. force-file-writefalse When set to force-file-write: true, mockery will forcibly overwrite any existing files. formatter\"goimports\" The formatter to use on the rendered template. Choices are: gofmt, goimports, noop. include-regex\"\" When set, only interface names that match the expression will be generated. This setting is ignored if all: True is specified in the configuration. To further refine the interfaces generated, use exclude-regex. log-level\"info\" Set the level of the logger mockname\"Mock{{.InterfaceName}}\" The name of the generated mock. outpkg\"{{.PackageName}}\" Use outpkg to specify the package name of the generated mocks. packagesnull A dictionary containing configuration describing the packages and interfaces to generate mocks for. pkgname\"{{.SrcPackageName}}\" | The#!go package name` given to the generated mock files. recursivefalse When set to true on a particular package, mockery will recursively search for all sub-packages and inject those packages into the config map. replace-type{} Use this parameter to specify type replacements. tags\"\" A space-separated list of additional build tags to load packages. template\"\" The template to use. The choices are moq, mockery, or a file path provided by file://path/to/file.txt. template-data{} A map[string]any that provides arbitrary options to the template. Each template will have a different set of accepted keys. Refer to each template's documentation for more details."},{"location":"configuration/#templates","title":"Templates","text":"
Parameters marked as being templated have access to a number of template variables and functions through the Go text/template system.
If a parameter is named enable-feature and we want a value of True, then these are the formats for each source:
source value command line --enable-feature=true Environment variable MOCKERY_ENABLE_FEATURE=True yaml enable-feature: True"},{"location":"faq/","title":"Frequently Asked Questions","text":""},{"location":"faq/#error-no-go-files-found-in-root-search-path","title":"error: no go files found in root search path","text":"
When using the packages feature, recursive: true and you have specified a package that contains no *.go files, mockery is unable to determine the on-disk location of the package in order to continue the recursive package search. This appears to be a limitation of the golang.org/x/tools/go/packages package that is used to parse package metadata.
The solution is to create a .go file in the package's path and add a package [name] directive at the top. It doesn't matter what the file is called. This allows mockery to properly read package metadata.
Discussion
"},{"location":"faq/#internal-error-package-without-types-was-imported","title":"internal error: package without types was imported","text":"
https://github.com/vektra/mockery/issues/475
This issue indicates that you have attempted to use package in your dependency tree (whether direct or indirect) that uses Go language semantics that your currently-running Go version does not support. The solution:
Update to the latest go version
Delete all cached packages with go clean -modcache
Reinstall mockery
Additionally, this issue only happens when compiling mockery from source, such as with go install. Our docs recommend not to use go install as the success of your build depends on the compatibility of your Go version with the semantics in use. You would not encounter this issue if using one of the installation methods that install pre-built binaries, like downloading the .tar.gz binaries, or through brew install.
"},{"location":"faq/#multiple-expectations-with-identical-arguments","title":"Multiple Expectations With Identical Arguments","text":"
There might be instances where you want a mock to return different values on successive calls that provide the same arguments. For example, we might want to test this behavior:
Go
// Return \"foo\" on the first call\ngetter := NewGetter()\nassert(t, \"foo\", getter.Get(\"key\"))\n\n// Return \"bar\" on the second call\nassert(t, \"bar\", getter.Get(\"key\"))\n
This can be done by using the .Once() method on the mock call expectation:
Consider if we have a function func Bar(message ...string) error. A typical assertion might look like this:
Go
func TestFoo(t *testing.T) {\n m := NewMockFoo(t)\n m.On(\"Bar\", \"hello\", \"world\").Return(nil)\n
We might also want to make an assertion that says \"any number of variadic arguments\":
Go
m.On(\"Bar\", mock.Anything).Return(nil)\n
However, what we've given to mockery is ambiguous because it is impossible to distinguish between these two intentions:
Any number of variadic arguments of any value
A single variadic argument of any value
This is fixed in #359 where you can provide unroll-variadic: False to get back to the old behavior. Thus, if you want to assert (1), you can then do:
Go
m.On(\"Bar\", mock.Anything).Return(nil)\n
If you want to assert (2), you must set unroll-variadic: True. Then this assertion's intention will be modified to mean the second case:
Go
m.On(\"Bar\", mock.Anything).Return(nil)\n
An upstream patch to testify is currently underway to allow passing mock.Anything directly to the variadic slice: https://github.com/stretchr/testify/pull/1348
If this is merged, it would become possible to describe the above two cases respectively:
Go
// case 1\nm.On(\"Bar\", mock.Anything).Return(nil)\n// case 2\nm.On(\"Bar\", []interface{}{mock.Anything}).Return(nil)\n
The versioning in this project applies only to the behavior of the mockery binary itself. This project explicitly does not promise a stable internal API, but rather a stable executable. The versioning applies to the following:
CLI arguments.
Parsing of Go code. New features in the Go language will be supported in a backwards-compatible manner, except during major version bumps.
Behavior of mock objects. Mock objects can be considered to be part of the public API.
Behavior of mockery given a set of arguments.
What the version does not track:
The interfaces, objects, methods etc. in the vektra/mockery package.
Compatibility of go get-ing mockery with new or old versions of Go.
"},{"location":"faq/#mocking-interfaces-in-main","title":"Mocking interfaces in main","text":"
When your interfaces are in the main package, you should supply the --inpackage flag. This will generate mocks in the same package as the target code, avoiding import issues.
"},{"location":"faq/#mockery-fails-to-run-when-mockery_version-environment-variable-is-set","title":"mockery fails to run when MOCKERY_VERSION environment variable is set","text":"
This issue was first highlighted in this GitHub issue.
mockery uses the viper package for configuration mapping and parsing. Viper is set to automatically search for all config variables specified in its config struct. One of the config variables is named version, which gets mapped to an environment variable called MOCKERY_VERSION. If you set this environment variable, mockery attempts to parse it into the version bool config.
This is an adverse effect of how our config parsing is set up. The solution is to rename your environment variable to something other than MOCKERY_VERSION.
The mock will now replace all instances of rt1.RType1 with rt2.RType2. You can see the before and after of mockery-style mocks:
beforeafter Go
// Replace2 provides a mock function for the type RTypeReplaced1\nfunc (_mock *RTypeReplaced1) Replace1(f rt1.RType1) {\n _mock.Called(f)\n return\n}\n
Go
// Replace2 provides a mock function for the type RTypeReplaced1\nfunc (_mock *RTypeReplaced1) Replace1(f rt2.RType2) {\n _mock.Called(f)\n return\n}\n
This parameter is useful if you need to need to work around packages that use internal types. Take for example the situation found here, noted by RangelReale.
If your .mockery.yaml file has been populated with the packages and interfaces you want mocked, mockery can be run with no arguments. Take for example how the mockery project itself is configured:
From anywhere within your repo, you can simply call mockery once, and it will find your config either by respecting the config path you gave it, or by searching upwards from the current working directory.
Mockery releases version 3 of the project that provides a number of high-profile benefits over v2:
Allows generation of matryer-style templates. The https://github.com/matryer/moq project is being folded into mockery to combine the speed and configuration flexibility of mockery with the simplicity of moq-style mocks.
Changes the generation scheme to be entirely driven off of Go templates. This means that the data provided to templates is considered as part of the public API.
Mockery now allows users to specify their own templates to make code generation far easier. Mockery handles the problem of parsing source code and enables you to focus on creating your own interface implementations.
Shedding all deprecated variables and simplifying the way in which mocks are configured.
Mockery, in its essence, renders templates. This project provides a number of pre-curated templates that you can select with the template: config parameter.
matryer templates draw from the mocks generated from the project at https://github.com/matryer/moq. This project was folded into mockery, and thus moq-style mocks can be natively generated from within mockery.
Mocks generated using this template allow you to define precise functions to be run. Example:
You may also provide mockery a path to your own file using the file:// protocol specifier. The string after file:// will be the relative or absolute path of your template.
The templates are rendered with the data as shown in the section below.
You can see examples of how the mockery project utilizes the template system to generate the different mock styles:
The template is supplied with the template.Data struct. Some attributes return types such as template.MockData and template.Package which themselves contain methods that may also be called.
"},{"location":"template/matryer/","title":"matryer/moq","text":""},{"location":"template/matryer/#description","title":"Description","text":"Interface.mockery.ymlmocks_moq.goExample Usage Go
// Code generated by mockery; DO NOT EDIT.\n// github.com/vektra/mockery\n\npackage test\n\nimport (\n \"sync\"\n)\n\n// Ensure, that MoqRequester does implement Requester.\n// If this is not the case, regenerate this file with moq.\nvar _ Requester = &MoqRequester{}\n\n// MoqRequester is a mock implementation of Requester.\n//\n// func TestSomethingThatUsesRequester(t *testing.T) {\n//\n// // make and configure a mocked Requester\n// mockedRequester := &MoqRequester{\n// GetFunc: func(path string) (string, error) {\n// panic(\"mock out the Get method\")\n// },\n// }\n//\n// // use mockedRequester in code that requires Requester\n// // and then make assertions.\n//\n// }\ntype MoqRequester struct {\n // GetFunc mocks the Get method.\n GetFunc func(path string) (string, error)\n\n // calls tracks calls to the methods.\n calls struct {\n // Get holds details about calls to the Get method.\n Get []struct {\n // Path is the path argument value.\n Path string\n }\n }\n lockGet sync.RWMutex\n}\n\n// Get calls GetFunc.\nfunc (mock *MoqRequester) Get(path string) (string, error) {\n // ...\n}\n\n// GetCalls gets all the calls that were made to Get.\n// Check the length with:\n//\n// len(mockedRequester.GetCalls())\nfunc (mock *MoqRequester) GetCalls() []struct {\n Path string\n} {\n // ...\n}\n
Moq-style mocks are far simpler, and probably more intuitive, than testify-style mocks. All that's needed is to define the function that will be run when the mock's method is called.
key type description boilerplate-filestring Specify a path to a file that contains comments you want displayed at the top of all generated mock files. This is commonly used to display license headers at the top of your source code. mock-build-tags\"\" Set the build tags of the generated mocks. Read more about the format. skip-ensurebool Suppress mock implementation check, avoid import cycle if mocks generated outside of the tested package. stub-implbool Return zero values when no mock implementation is provided, do not panic. with-resetsbool Generates methods that allow resetting calls made to the mocks."},{"location":"template/testify/","title":"Mockery","text":"
Features for template: testify.
Choosing this template will render a traditional \"mockery-style\" template. The section below shows what will be rendered for the given interface.
"},{"location":"template/testify/#description","title":"Description","text":"Interface.mockery.ymlmocks.goExample Usage Go
// Code generated by mockery; DO NOT EDIT.\n// github.com/vektra/mockery\n\npackage test\n\nimport (\n mock \"github.com/stretchr/testify/mock\"\n)\n\n\n// NewRequester creates a new instance of Requester. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.\n// The first argument is typically a *testing.T value.\nfunc NewRequester (t interface {\n mock.TestingT\n Cleanup(func())\n}) *Requester {\n // ...\n}\n\n\n// Requester is an autogenerated mock type for the Requester type\ntype Requester struct {\n mock.Mock\n}\n\ntype Requester_Expecter struct {\n mock *mock.Mock\n}\n\nfunc (_m *Requester) EXPECT() *Requester_Expecter {\n // ...\n}\n\n\n\n// Get provides a mock function for the type Requester\nfunc (_mock *Requester) Get(path string) (string, error) {\n // ...\n}\n\n\n\n// Requester_Get_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Get'\ntype Requester_Get_Call struct {\n *mock.Call\n}\n\n\n\n// Get is a helper method to define mock.On call\n// - path\nfunc (_e *Requester_Expecter) Get(path interface{}, ) *Requester_Get_Call {\n // ...\n}\n\nfunc (_c *Requester_Get_Call) Run(run func(path string)) *Requester_Get_Call {\n // ...\n}\n\nfunc (_c *Requester_Get_Call) Return(s string, err error) *Requester_Get_Call {\n // ...\n}\n\nfunc (_c *Requester_Get_Call) RunAndReturn(run func(path string)(string, error)) *Requester_Get_Call {\n // ...\n}\n
As you can see, this mock utilizes github.com/stretchr/testify under the hood and registers call expectations with testify. When the mock receives a call to Get(), it retrieves the expected value from testify to be returned.
This style of mock also has other interesting methods:
"},{"location":"template/testify/#template-data","title":"template-data","text":"key type description boilerplate-filestring Specify a path to a file that contains comments you want displayed at the top of all generated mock files. This is commonly used to display license headers at the top of your source code. mock-build-tags\"\" Set the build tags of the generated mocks. Read more about the format. unroll-variadicbool If set to unroll-variadic: true, will expand the variadic argument to testify using the ... syntax. See notes for more details."},{"location":"template/testify/#features","title":"Features","text":""},{"location":"template/testify/#replace-types","title":"Replace Types","text":"
v2.23.0
The replace-type parameter allows adding a list of type replacements to be made in package and/or type names. This can help overcome issues like usage of type aliases that point to internal packages.
This will replace any imported named \"github.com/vektra/mockery/v3/baz/internal/foo\" with baz \"github.com/vektra/mockery/v3/baz\". The alias is defined with : before the package name. Also, the InternalBaz type that comes from this package will be renamed to baz.Baz.
This next example fixes a common problem of type aliases that point to an internal package.
cloud.google.com/go/pubsub.Message is a type alias defined like this:
The Go parser that mockery uses doesn't provide a way to detect this alias and sends the application the package and type name of the type in the internal package, which will not work.
We can use replace-type with only the package part to replace any import of cloud.google.com/go/internal/pubsub to cloud.google.com/go/pubsub. We don't need to change the alias or type name in this case, because they are pubsub and Message in both cases.
type InternalBaz[T any] struct{}\n\nfunc (*InternalBaz[T]) Foo() T {}\n\n// Becomes\ntype InternalBaz[T baz.Baz] struct{}\n\nfunc (*InternalBaz[T]) Foo() T {}\n
If a type constraint needs to be removed and replaced with a type, target the constraint with square brackets and include a '-' in front to have it removed.
All mock objects have constructor functions. These constructors do basic test setup so that the expectations you set in the code are asserted before the test exits.
Previously something like this would need to be done: Go
factory := &mocks.Factory{}\nfactory.Test(t) // so that mock does not panic when a method is unexpected\ndefer factory.AssertExpectations(t)\n
Instead, you may simply use the constructor: Go
factory := mocks.NewFactory(t)\n
The constructor sets up common functionalities automatically
The AssertExpectations method is registered to be called at the end of the tests via t.Cleanup() method.
The testing.TB interface is registered on the mock.Mock so that tests don't panic when a call on the mock is unexpected.
Mockery now supports an \"expecter\" struct, which allows your tests to use type-safe methods to generate call expectations. When enabled through the with-expecter: True mockery configuration, you can enter into the expecter interface by simply calling .EXPECT() on your mock object.
For example, given an interface such as Go
type Requester interface {\n Get(path string) (string, error)\n}\n
A RunAndReturn method is also available on the expecter struct that allows you to dynamically set a return value based on the input to the mock's call.
Note that the types of the arguments on the EXPECT methods are interface{}, not the actual type of your interface. The reason for this is that you may want to pass mock.Any as an argument, which means that the argument you pass may be an arbitrary type. The types are still provided in the expecter method docstrings.
"},{"location":"template/testify/#return-value-providers","title":"Return Value Providers","text":"
v2.20.0
Return Value Providers can be used one of two ways. You may either define a single function with the exact same signature (number and type of input and return parameters) and pass that as a single value to Return, or you may pass multiple values to Return (one for each return parameter of the mocked function.) If you are using the second form, for each of the return values of the mocked function, Return needs a function which takes the same arguments as the mocked function, and returns one of the return values. For example, if the return argument signature of passthrough in the above example was instead (string, error) in the interface, Return would also need a second function argument to define the error value:
Go
type Proxy interface {\n passthrough(ctx context.Context, s string) (string, error)\n}\n
"}]}
\ No newline at end of file
+{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"],"fields":{"title":{"boost":1000.0},"text":{"boost":1.0},"tags":{"boost":1000000.0}}},"docs":[{"location":"","title":"mockery","text":"
Alpha Test
Mockery v3 is currently in alpha and should not be used for production.
Mockery is a project that creates mock implementations of Golang interfaces. It inspects source code and generates implementations of the interface that aid in testing.
In addition to providing a number of different styles of mocks, mockery also allows users to provide their own template files that will then be rendered using a set of template data, methods, and functions that provide comprehensive typing information about the Go interface in question.
"},{"location":"#why-use-mockery","title":"Why use mockery?","text":"
You gain access to a number of pre-curated mock implementations that can be used in testing. This includes traditional \"mockery-style\" mocks, as well as other styles from the open source community such as from https://github.com/matryer/moq. Such mocks allow you to quickly define how the implementation should behave under test without having to manually curate your own mocks/stubs/fakes.
Mockery benefits from a large number of performance improvements that almost all other Go code-generation projects currently have not employed. This means that it's orders of magnitude faster for large codebases.
Mockery provides a comprehensive, centralized, flexible, and simple configuration scheme driven off of yaml instead of relying on sprawling //go:generate commands.
Mockery is a code-generation framework. While its original goal is to provide mock implementations for testing purposes, users can supply their own templates to auto-generate any kind of code that needs to be based off of interfaces.
A number of high profile companies, projects, and communities trust Mockery.
All configuration is specified in a .mockery.yml file. An example config file may look like this:
YAML
all: False\ntemplate-data:\n boilerplate-file: ./path/to/boilerplate.txt\ntemplate: mockery\npackages:\n github.com/vektra/example:\n config:\n # Make use of the template variables to place the mock in the same\n # directory as the original interface.\n dir: \"{{.InterfaceDir}}\"\n filename: \"mocks_test.go\"\n outpkg: \"{{.PackageName}}_test\"\n mockname: \"Mock{{.InterfaceName}}\"\n interfaces:\n Foo:\n Bar:\n config:\n # Make it unexported instead\n mockname: \"mock{{.InterfaceName}}\"\n Baz:\n # Create two mock implementations of Baz with different names.\n configs:\n - filename: \"mocks_baz_one_test.go\"\n mockname: \"MockBazOne\"\n - filename: \"mocks_baz_two_test.go\"\n mockname: \"MockBazTwo\"\n io:\n config:\n dir: path/to/io/mocks\n filename: \"mocks_io.go\"\n
These are the highlights of the config scheme:
The parameters are merged hierarchically
There are a number of template variables available to generalize config values.
The style of mock to be generated is specified using the template parameter.
An output file may contain multiple mocks, but the only rule is that all the mocks in the file must come from the same package. Because of this, mocks for different packages must go in different files.
"},{"location":"configuration/#parameter-descriptions","title":"Parameter Descriptions","text":"name templated default description allfalse Generate all interfaces for the specified packages. _anchors{} Unused by mockery, but allowed in the config schema so that you may define arbitrary yaml anchors. config\"\" Set the location of the mockery config file. dir\"mocks/{{.SrcPackagePath}}\" The directory where the mock file will be outputted to. exclude-subpkg-regex[] A list of regular expressions that denote which subpackages should be excluded when recursive: trueexclude-regex\"\" When set along with include-regex, then interfaces which match include-regex but also match exclude-regex will not be generated. If all is set, or if include-regex is not set, then exclude-regex has no effect. filename\"mock_{{.InterfaceName}}.go\" The name of the file the mock will reside in. force-file-writefalse When set to force-file-write: true, mockery will forcibly overwrite any existing files. formatter\"goimports\" The formatter to use on the rendered template. Choices are: gofmt, goimports, noop. include-regex\"\" When set, only interface names that match the expression will be generated. This setting is ignored if all: True is specified in the configuration. To further refine the interfaces generated, use exclude-regex. log-level\"info\" Set the level of the logger mockname\"Mock{{.InterfaceName}}\" The name of the generated mock. outpkg\"{{.PackageName}}\" Use outpkg to specify the package name of the generated mocks. packagesnull A dictionary containing configuration describing the packages and interfaces to generate mocks for. pkgname\"{{.SrcPackageName}}\" | The#!go package name` given to the generated mock files. recursivefalse When set to true on a particular package, mockery will recursively search for all sub-packages and inject those packages into the config map. replace-type{} Use this parameter to specify type replacements. tags\"\" A space-separated list of additional build tags to load packages. template\"\" The template to use. The choices are moq, mockery, or a file path provided by file://path/to/file.txt. template-data{} A map[string]any that provides arbitrary options to the template. Each template will have a different set of accepted keys. Refer to each template's documentation for more details."},{"location":"configuration/#templates","title":"Templates","text":"
Parameters marked as being templated have access to a number of template variables and functions through the Go text/template system.
If a parameter is named enable-feature and we want a value of True, then these are the formats for each source:
source value command line --enable-feature=true Environment variable MOCKERY_ENABLE_FEATURE=True yaml enable-feature: True"},{"location":"faq/","title":"Frequently Asked Questions","text":""},{"location":"faq/#error-no-go-files-found-in-root-search-path","title":"error: no go files found in root search path","text":"
When using the packages feature, recursive: true and you have specified a package that contains no *.go files, mockery is unable to determine the on-disk location of the package in order to continue the recursive package search. This appears to be a limitation of the golang.org/x/tools/go/packages package that is used to parse package metadata.
The solution is to create a .go file in the package's path and add a package [name] directive at the top. It doesn't matter what the file is called. This allows mockery to properly read package metadata.
Discussion
"},{"location":"faq/#internal-error-package-without-types-was-imported","title":"internal error: package without types was imported","text":"
https://github.com/vektra/mockery/issues/475
This issue indicates that you have attempted to use package in your dependency tree (whether direct or indirect) that uses Go language semantics that your currently-running Go version does not support. The solution:
Update to the latest go version
Delete all cached packages with go clean -modcache
Reinstall mockery
Additionally, this issue only happens when compiling mockery from source, such as with go install. Our docs recommend not to use go install as the success of your build depends on the compatibility of your Go version with the semantics in use. You would not encounter this issue if using one of the installation methods that install pre-built binaries, like downloading the .tar.gz binaries, or through brew install.
The mockery project follows the standard Semantic Versioning Semantics. The versioning applies to the following areas:
The shape of mocks generated by pre-curated templates.
Functions and data provided to templates specified with template: \"file://\".
Configuration options.
Mockery is not meant to be used as an imported library. Importing mockery code in external modules is not supported.
"},{"location":"faq/#mocking-interfaces-in-main","title":"Mocking interfaces in main","text":"
When your interfaces are in the main package, you should supply the --inpackage flag. This will generate mocks in the same package as the target code, avoiding import issues.
"},{"location":"faq/#mockery-fails-to-run-when-mockery_version-environment-variable-is-set","title":"mockery fails to run when MOCKERY_VERSION environment variable is set","text":"
This issue was first highlighted in this GitHub issue.
mockery uses the viper package for configuration mapping and parsing. Viper is set to automatically search for all config variables specified in its config struct. One of the config variables is named version, which gets mapped to an environment variable called MOCKERY_VERSION. If you set this environment variable, mockery attempts to parse it into the version bool config.
This is an adverse effect of how our config parsing is set up. The solution is to rename your environment variable to something other than MOCKERY_VERSION.
The mock will now replace all instances of rt1.RType1 with rt2.RType2. You can see the before and after of mockery-style mocks:
beforeafter Go
// Replace2 provides a mock function for the type RTypeReplaced1\nfunc (_mock *RTypeReplaced1) Replace1(f rt1.RType1) {\n _mock.Called(f)\n return\n}\n
Go
// Replace2 provides a mock function for the type RTypeReplaced1\nfunc (_mock *RTypeReplaced1) Replace1(f rt2.RType2) {\n _mock.Called(f)\n return\n}\n
This parameter is useful if you need to need to work around packages that use internal types. Take for example the situation found here, noted by RangelReale.
If your .mockery.yaml file has been populated with the packages and interfaces you want mocked, mockery can be run with no arguments. Take for example how the mockery project itself is configured:
From anywhere within your repo, you can simply call mockery once, and it will find your config either by respecting the config path you gave it, or by searching upwards from the current working directory.
Mockery releases version 3 of the project that provides a number of high-profile benefits over v2:
Allows generation of matryer-style templates. The https://github.com/matryer/moq project is being subsumed into mockery to combine the speed and configuration flexibility of mockery with the simplicity of moq-style mocks.
Changes the generation scheme to be entirely driven off of Go templates. This means that the data provided to templates is considered as part of the public API.
Mockery now allows users to specify their own templates to make code generation far easier. Mockery handles the problem of parsing source code and enables you to focus on creating your own interface implementations.
Shedding all deprecated variables and simplifying the way in which mocks are configured.
In v3, mockery is capable of producing two styles of mocks. In v3, the mockery-style mocks are called testify and can be used by setting template: testify. The shape of the mocks should be identical (minus the now-required expecter methods) and should not require any changes to existing tests using testify-style mocks.(1)
If this is not the case and the v3 testify-style mocks have breaking changes, please submit an issue on Github.
Mockery v2 has explicitly deprecated a number of variables. These deprecations can be found here: https://vektra.github.io/mockery/latest-v2/deprecations/. Mockery logs warnings such as:
20 Jan 25 15:53 CST WRN DEPRECATION: disable-version-string will be permanently set to True in v3 deprecation-name=disable-version-string url=https://vektra.github.io/mockery/v0.0/deprecations/#disable-version-string version=v0.0.0-dev\n20 Jan 25 15:53 CST WRN DEPRECATION: issue-845-fix must be set to True to remove this warning. Visit the link for more details. deprecation-name=issue-845-fix url=https://vektra.github.io/mockery/v0.0/deprecations/#issue-845-fix version=v0.0.0-dev\n20 Jan 25 15:53 CST WRN DEPRECATION: resolve-type-alias will be permanently set to False in v3. Please modify your config to set the parameter to False. deprecation-name=resolve-type-alias url=https://vektra.github.io/mockery/v0.0/deprecations/#resolve-type-alias version=v0.0.0-dev\n20 Jan 25 15:53 CST WRN DEPRECATION: with-expecter will be permanently set to True in v3 deprecation-name=with-expecter url=https://vektra.github.io/mockery/v0.0/deprecations/#with-expecter version=v0.0.0-dev\n
These warnings provide doc URLs that indicate how to fix the warning to prepare for the v3 release. While we provide these warnings on a best-effort basis, they are unlikely to be comprehensive due to the large number of changes that v3 introduces. Please submit an issue on Github if you notice a missing deprecation warning that would be useful to have.
In v2, mockery defaulted to placing mocks in a separate mocks/ directory as shown here. In v3, mockery will by default place mocks adjacent to the mocked interface.
It is still possible to place mocks in a separate directory by making use of the template variables and functions available to the configuration parameters.
Mockery v2 has an inpackage parameter that informed mockery when a mock was being generated in the same package as the original interface. In v3, this parameter has been removed as mockery is now able to detect when the mock is placed in the same package.
Mockery v2 provided a keeptree parameter that was deprecated and used only in the pre-packages config schema. This parameter has no use in v3 and has been removed.
The replace-type: parameter has an updated schema. In v2, users provided a list of strings, where each string needed to confirm to a specific format that was parsed at runtime. In v3, the schema is more explicit to make it simpler.
This parameter has been moved under the template-data: parameter. Parameters that apply only to specific templates are not expressed in the top-level schema and are instead passed through the schemaless template-data: map.
Mockery, in its essence, renders templates. This project provides a number of pre-curated templates that you can select with the template: config parameter.
matryer templates draw from the mocks generated from the project at https://github.com/matryer/moq. This project was folded into mockery, and thus moq-style mocks can be natively generated from within mockery.
Mocks generated using this template allow you to define precise functions to be run. Example:
You may also provide mockery a path to your own file using the file:// protocol specifier. The string after file:// will be the relative or absolute path of your template.
The templates are rendered with the data as shown in the section below.
You can see examples of how the mockery project utilizes the template system to generate the different mock styles:
The template is supplied with the template.Data struct. Some attributes return types such as template.MockData and template.Package which themselves contain methods that may also be called.
"},{"location":"template/matryer/","title":"matryer/moq","text":""},{"location":"template/matryer/#description","title":"Description","text":"Interface.mockery.ymlmocks_moq.goExample Usage Go
// Code generated by mockery; DO NOT EDIT.\n// github.com/vektra/mockery\n\npackage test\n\nimport (\n \"sync\"\n)\n\n// Ensure, that MoqRequester does implement Requester.\n// If this is not the case, regenerate this file with moq.\nvar _ Requester = &MoqRequester{}\n\n// MoqRequester is a mock implementation of Requester.\n//\n// func TestSomethingThatUsesRequester(t *testing.T) {\n//\n// // make and configure a mocked Requester\n// mockedRequester := &MoqRequester{\n// GetFunc: func(path string) (string, error) {\n// panic(\"mock out the Get method\")\n// },\n// }\n//\n// // use mockedRequester in code that requires Requester\n// // and then make assertions.\n//\n// }\ntype MoqRequester struct {\n // GetFunc mocks the Get method.\n GetFunc func(path string) (string, error)\n\n // calls tracks calls to the methods.\n calls struct {\n // Get holds details about calls to the Get method.\n Get []struct {\n // Path is the path argument value.\n Path string\n }\n }\n lockGet sync.RWMutex\n}\n\n// Get calls GetFunc.\nfunc (mock *MoqRequester) Get(path string) (string, error) {\n // ...\n}\n\n// GetCalls gets all the calls that were made to Get.\n// Check the length with:\n//\n// len(mockedRequester.GetCalls())\nfunc (mock *MoqRequester) GetCalls() []struct {\n Path string\n} {\n // ...\n}\n
Moq-style mocks are far simpler, and probably more intuitive, than testify-style mocks. All that's needed is to define the function that will be run when the mock's method is called.
key type description boilerplate-filestring Specify a path to a file that contains comments you want displayed at the top of all generated mock files. This is commonly used to display license headers at the top of your source code. mock-build-tags\"\" Set the build tags of the generated mocks. Read more about the format. skip-ensurebool Suppress mock implementation check, avoid import cycle if mocks generated outside of the tested package. stub-implbool Return zero values when no mock implementation is provided, do not panic. with-resetsbool Generates methods that allow resetting calls made to the mocks."},{"location":"template/testify/","title":"Mockery","text":"
Features for template: testify.
Choosing this template will render a traditional \"mockery-style\" template. The section below shows what will be rendered for the given interface.
"},{"location":"template/testify/#description","title":"Description","text":"Interface.mockery.ymlmocks.goExample Usage Go
// Code generated by mockery; DO NOT EDIT.\n// github.com/vektra/mockery\n\npackage test\n\nimport (\n mock \"github.com/stretchr/testify/mock\"\n)\n\n\n// NewRequester creates a new instance of Requester. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.\n// The first argument is typically a *testing.T value.\nfunc NewRequester (t interface {\n mock.TestingT\n Cleanup(func())\n}) *Requester {\n // ...\n}\n\n\n// Requester is an autogenerated mock type for the Requester type\ntype Requester struct {\n mock.Mock\n}\n\ntype Requester_Expecter struct {\n mock *mock.Mock\n}\n\nfunc (_m *Requester) EXPECT() *Requester_Expecter {\n // ...\n}\n\n\n\n// Get provides a mock function for the type Requester\nfunc (_mock *Requester) Get(path string) (string, error) {\n // ...\n}\n\n\n\n// Requester_Get_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Get'\ntype Requester_Get_Call struct {\n *mock.Call\n}\n\n\n\n// Get is a helper method to define mock.On call\n// - path\nfunc (_e *Requester_Expecter) Get(path interface{}, ) *Requester_Get_Call {\n // ...\n}\n\nfunc (_c *Requester_Get_Call) Run(run func(path string)) *Requester_Get_Call {\n // ...\n}\n\nfunc (_c *Requester_Get_Call) Return(s string, err error) *Requester_Get_Call {\n // ...\n}\n\nfunc (_c *Requester_Get_Call) RunAndReturn(run func(path string)(string, error)) *Requester_Get_Call {\n // ...\n}\n
As you can see, this mock utilizes github.com/stretchr/testify under the hood and registers call expectations with testify. When the mock receives a call to Get(), it retrieves the expected value from testify to be returned.
This style of mock also has other interesting methods:
"},{"location":"template/testify/#template-data","title":"template-data","text":"key type description boilerplate-filestring Specify a path to a file that contains comments you want displayed at the top of all generated mock files. This is commonly used to display license headers at the top of your source code. mock-build-tags\"\" Set the build tags of the generated mocks. Read more about the format. unroll-variadicbool If set to unroll-variadic: true, will expand the variadic argument to testify using the ... syntax. See notes for more details."},{"location":"template/testify/#features","title":"Features","text":""},{"location":"template/testify/#mock-constructors","title":"Mock Constructors","text":"
v2.11.0
All mock objects have constructor functions. These constructors do basic test setup so that the expectations you set in the code are asserted before the test exits.
Previously something like this would need to be done: Go
factory := &mocks.Factory{}\nfactory.Test(t) // so that mock does not panic when a method is unexpected\ndefer factory.AssertExpectations(t)\n
Instead, you may simply use the constructor: Go
factory := mocks.NewFactory(t)\n
The constructor sets up common functionalities automatically
The AssertExpectations method is registered to be called at the end of the tests via t.Cleanup() method.
The testing.TB interface is registered on the mock.Mock so that tests don't panic when a call on the mock is unexpected.
Mockery now supports an \"expecter\" struct, which allows your tests to use type-safe methods to generate call expectations. When enabled through the with-expecter: True mockery configuration, you can enter into the expecter interface by simply calling .EXPECT() on your mock object.
For example, given an interface such as Go
type Requester interface {\n Get(path string) (string, error)\n}\n
A RunAndReturn method is also available on the expecter struct that allows you to dynamically set a return value based on the input to the mock's call.
Note that the types of the arguments on the EXPECT methods are interface{}, not the actual type of your interface. The reason for this is that you may want to pass mock.Any as an argument, which means that the argument you pass may be an arbitrary type. The types are still provided in the expecter method docstrings.
"},{"location":"template/testify/#return-value-providers","title":"Return Value Providers","text":"
v2.20.0
Return Value Providers can be used one of two ways. You may either define a single function with the exact same signature (number and type of input and return parameters) and pass that as a single value to Return, or you may pass multiple values to Return (one for each return parameter of the mocked function.) If you are using the second form, for each of the return values of the mocked function, Return needs a function which takes the same arguments as the mocked function, and returns one of the return values. For example, if the return argument signature of passthrough in the above example was instead (string, error) in the interface, Return would also need a second function argument to define the error value:
Go
type Proxy interface {\n passthrough(ctx context.Context, s string) (string, error)\n}\n
Consider if we have a function func Bar(message ...string) error. A typical assertion might look like this:
Go
func TestFoo(t *testing.T) {\n m := NewMockFoo(t)\n m.On(\"Bar\", \"hello\", \"world\").Return(nil)\n
We might also want to make an assertion that says \"any number of variadic arguments\":
Go
m.On(\"Bar\", mock.Anything).Return(nil)\n
However, what we've given to mockery is ambiguous because it is impossible to distinguish between these two intentions:
Any number of variadic arguments of any value
A single variadic argument of any value
This is fixed in #359 where you can provide unroll-variadic: False to get back to the old behavior. Thus, if you want to assert (1), you can then do:
Go
m.On(\"Bar\", mock.Anything).Return(nil)\n
If you want to assert (2), you must set unroll-variadic: True. Then this assertion's intention will be modified to mean the second case:
Go
m.On(\"Bar\", mock.Anything).Return(nil)\n
An upstream patch to testify is currently underway to allow passing mock.Anything directly to the variadic slice: https://github.com/stretchr/testify/pull/1348
If this is merged, it would become possible to describe the above two cases respectively:
Go
// case 1\nm.On(\"Bar\", mock.Anything).Return(nil)\n// case 2\nm.On(\"Bar\", []interface{}{mock.Anything}).Return(nil)\n
References:
https://github.com/vektra/mockery/pull/359
https://github.com/vektra/mockery/pull/123
https://github.com/vektra/mockery/pull/550
https://github.com/vektra/mockery/issues/541
"},{"location":"template/testify/#multiple-expectations-with-identical-arguments","title":"Multiple Expectations With Identical Arguments","text":"
There might be instances where you want a mock to return different values on successive calls that provide the same arguments. For example, we might want to test this behavior:
Go
// Return \"foo\" on the first call\ngetter := NewGetter()\nassert(t, \"foo\", getter.Get(\"key\"))\n\n// Return \"bar\" on the second call\nassert(t, \"bar\", getter.Get(\"key\"))\n
This can be done by using the .Once() method on the mock call expectation:
Note that with proper Go support in your IDE, all the available methods are self-documented in autocompletion help contexts.
"}]}
\ No newline at end of file
diff --git a/v3.0/template/index.html b/v3.0/template/index.html
index 97375f88..b0908fc6 100644
--- a/v3.0/template/index.html
+++ b/v3.0/template/index.html
@@ -982,7 +982,7 @@
matryer templates draw from the mocks generated from the project at https://github.com/matryer/moq. This project was folded into mockery, and thus moq-style mocks can be natively generated from within mockery.
+
matryer templates draw from the mocks generated from the project at https://github.com/matryer/moq. This project was folded into mockery, and thus moq-style mocks can be natively generated from within mockery.
Mocks generated using this template allow you to define precise functions to be run. Example:
The replace-type parameter allows adding a list of type replacements to be made in package and/or type names.
-This can help overcome issues like usage of type aliases that point to internal packages.
This will replace any imported named "github.com/vektra/mockery/v3/baz/internal/foo"
-with baz "github.com/vektra/mockery/v3/baz". The alias is defined with : before
-the package name. Also, the InternalBaz type that comes from this package will be renamed to baz.Baz.
-
This next example fixes a common problem of type aliases that point to an internal package.
-
cloud.google.com/go/pubsub.Message is a type alias defined like this:
The Go parser that mockery uses doesn't provide a way to detect this alias and sends the application the package and
-type name of the type in the internal package, which will not work.
-
We can use replace-type with only the package part to replace any import of cloud.google.com/go/internal/pubsub to
-cloud.google.com/go/pubsub. We don't need to change the alias or type name in this case, because they are pubsub
-and Message in both cases.
If a type constraint needs to be removed and replaced with a type, target the constraint with square brackets and include a '-' in front to have it removed.
All mock objects have constructor functions. These constructors do basic test setup so that the expectations you set in the code are asserted before the test exits.
Previously something like this would need to be done:
-
Go
factory:=&mocks.Factory{}
-factory.Test(t)// so that mock does not panic when a method is unexpected
-deferfactory.AssertExpectations(t)
+
Go
factory:=&mocks.Factory{}
+factory.Test(t)// so that mock does not panic when a method is unexpected
+deferfactory.AssertExpectations(t)
Instead, you may simply use the constructor:
-
Go
factory:=mocks.NewFactory(t)
+
Go
factory:=mocks.NewFactory(t)
The constructor sets up common functionalities automatically
A RunAndReturn method is also available on the expecter struct that allows you to dynamically set a return value based on the input to the mock's call.
-
Go
requesterMock.EXPECT().
-Get(mock.Anything).
-RunAndReturn(func(pathstring)(string,error){
-fmt.Println(path,"was called")
-return("result for "+path),nil
-})
+
Go
requesterMock.EXPECT().
+Get(mock.Anything).
+RunAndReturn(func(pathstring)(string,error){
+fmt.Println(path,"was called")
+return("result for "+path),nil
+})
Return Value Providers can be used one of two ways. You may either define a single function with the exact same signature (number and type of input and return parameters) and pass that as a single value to Return, or you may pass multiple values to Return (one for each return parameter of the mocked function.) If you are using the second form, for each of the return values of the mocked function, Return needs a function which takes the same arguments as the mocked function, and returns one of the return values. For example, if the return argument signature of passthrough in the above example was instead (string, error) in the interface, Return would also need a second function argument to define the error value:
There might be instances where you want a mock to return different values on successive calls that provide the same arguments. For example, we might want to test this behavior:
+
Go
// Return "foo" on the first call
+getter:=NewGetter()
+assert(t,"foo",getter.Get("key"))
+
+// Return "bar" on the second call
+assert(t,"bar",getter.Get("key"))
+
+
This can be done by using the .Once() method on the mock call expectation:
Mockery releases version 3 of the project that provides a number of high-profile benefits over v2:
-
Allows generation of matryer-style templates. The https://github.com/matryer/moq project is being folded into mockery to combine the speed and configuration flexibility of mockery with the simplicity of moq-style mocks.
+
Allows generation of matryer-style templates. The https://github.com/matryer/moq project is being subsumed into mockery to combine the speed and configuration flexibility of mockery with the simplicity of moq-style mocks.
Changes the generation scheme to be entirely driven off of Go templates. This means that the data provided to templates is considered as part of the public API.
Mockery now allows users to specify their own templates to make code generation far easier. Mockery handles the problem of parsing source code and enables you to focus on creating your own interface implementations.
Shedding all deprecated variables and simplifying the way in which mocks are configured.
In v3, mockery is capable of producing two styles of mocks. In v3, the mockery-style mocks are called testify and can be used by setting template:testify. The shape of the mocks should be identical (minus the now-required expecter methods) and should not require any changes to existing tests using testify-style mocks.(1)
+
+
If this is not the case and the v3 testify-style mocks have breaking changes, please submit an issue on Github.
20 Jan 25 15:53 CST WRN DEPRECATION: disable-version-string will be permanently set to True in v3 deprecation-name=disable-version-string url=https://vektra.github.io/mockery/v0.0/deprecations/#disable-version-string version=v0.0.0-dev
+20 Jan 25 15:53 CST WRN DEPRECATION: issue-845-fix must be set to True to remove this warning. Visit the link for more details. deprecation-name=issue-845-fix url=https://vektra.github.io/mockery/v0.0/deprecations/#issue-845-fix version=v0.0.0-dev
+20 Jan 25 15:53 CST WRN DEPRECATION: resolve-type-alias will be permanently set to False in v3. Please modify your config to set the parameter to False. deprecation-name=resolve-type-alias url=https://vektra.github.io/mockery/v0.0/deprecations/#resolve-type-alias version=v0.0.0-dev
+20 Jan 25 15:53 CST WRN DEPRECATION: with-expecter will be permanently set to True in v3 deprecation-name=with-expecter url=https://vektra.github.io/mockery/v0.0/deprecations/#with-expecter version=v0.0.0-dev
+
+
These warnings provide doc URLs that indicate how to fix the warning to prepare for the v3 release. While we provide these warnings on a best-effort basis, they are unlikely to be comprehensive due to the large number of changes that v3 introduces. Please submit an issue on Github if you notice a missing deprecation warning that would be useful to have.
In v2, mockery defaulted to placing mocks in a separate mocks/ directory as shown here. In v3, mockery will by default place mocks adjacent to the mocked interface.
+
It is still possible to place mocks in a separate directory by making use of the template variables and functions available to the configuration parameters.
Mockery v2 has an inpackage parameter that informed mockery when a mock was being generated in the same package as the original interface. In v3, this parameter has been removed as mockery is now able to detect when the mock is placed in the same package.
Mockery v2 provided a keeptree parameter that was deprecated and used only in the pre-packages config schema. This parameter has no use in v3 and has been removed.
The replace-type: parameter has an updated schema. In v2, users provided a list of strings, where each string needed to confirm to a specific format that was parsed at runtime. In v3, the schema is more explicit to make it simpler.
This parameter has been moved under the template-data: parameter. Parameters that apply only to specific templates are not expressed in the top-level schema and are instead passed through the schemaless template-data: map.