### Install Mockery using go install Source: https://vektra.github.io/mockery/latest-v3/installation Install Mockery using the go install command. It is recommended to use a specific version tag and avoid `@latest` to prevent issues with untagged commits. ```bash go install github.com/vektra/mockery/v3@v3.7.1 ``` -------------------------------- ### Basic Mock Setup with Testify Source: https://vektra.github.io/mockery/latest/template/testify Demonstrates the traditional setup for a mock object using Testify, including registering expectations for assertion. ```Go factory := &mocks.Factory{} factory.Test(t) // so that mock does not panic when a method is unexpected defer factory.AssertExpectations(t) ``` -------------------------------- ### Mock Constructor Setup Source: https://vektra.github.io/mockery/latest-v3/template/testify Use the constructor function for basic test setup, ensuring expectations are asserted and preventing panics on unexpected calls. ```Go factory := &mocks.Factory{} factory.Test(t) // so that mock does not panic when a method is unexpected defer factory.AssertExpectations(t) ``` ```Go factory := mocks.NewFactory(t) ``` -------------------------------- ### Install Mockery using Homebrew Source: https://vektra.github.io/mockery/latest-v3/installation Install or upgrade Mockery on macOS or Linux systems using the Homebrew package manager. ```bash brew install mockery ``` ```bash brew upgrade mockery ``` -------------------------------- ### Mock with Side Effect using Run Source: https://vektra.github.io/mockery/latest-v3/template/testify Demonstrates using the `Run` method to execute a side effect when the mock method is called. This example prints the argument passed to the `Get` method. ```Go func TestRequesterMockRun(t *testing.T) { m := NewMockRequester(t) m.EXPECT().Get(mock.Anything).Return("", nil) m.EXPECT().Get(mock.Anything).Run(func(path string) { fmt.Printf("Side effect! Argument is: %s", path) }) retString, err := m.Get("hello") assert.NoError(t, err) assert.Equal(t, retString, "") } ``` -------------------------------- ### Simplified Mock Creation with Constructor Source: https://vektra.github.io/mockery/latest/template/testify Shows how to use the mock constructor provided by Mockery for simplified test setup, automatically registering assertions and panic prevention. ```Go factory := mocks.NewFactory(t) ``` -------------------------------- ### Default Mockery Configuration File Source: https://vektra.github.io/mockery/latest-v3/configuration An example of a generated `.mockery.yml` file. It defines global settings and package-specific configurations. ```yaml all: false dir: '{{.InterfaceDir}}' filename: mocks_test.go force-file-write: false formatter: goimports log-level: info structname: '{{.Mock}}{{.InterfaceName}}' pkgname: '{{.SrcPackageName}}' recursive: false template: testify packages: github.com/vektra/mockery/v3/internal/fixtures: config: all: true ``` -------------------------------- ### Upgrade Mockery using Homebrew Source: https://vektra.github.io/mockery/latest/installation Upgrade an existing Mockery installation to the latest version using Homebrew. ```bash brew upgrade mockery ``` -------------------------------- ### Advanced Mockery YAML Configuration Source: https://vektra.github.io/mockery/latest/configuration An extensive YAML configuration example demonstrating advanced options like template data, custom filenames, package names, and multiple configurations for a single interface. ```yaml all: False template-data: boilerplate-file: ./path/to/boilerplate.txt template: testify packages: github.com/vektra/example: config: # Make use of the template variables to place the mock in the same # directory as the original interface. dir: "{{.InterfaceDir}}" filename: "mocks_test.go" pkgname: "{{.PackageName}}_test" structname: "{{.Mock}}{{.InterfaceName}}" interfaces: Foo: {} Bar: config: # Make it unexported instead structname: "mock{{.InterfaceName}}" Baz: # Create two mock implementations of Baz with different names. configs: - filename: "mocks_baz_one_test.go" structname: "MockBazOne" - filename: "mocks_baz_two_test.go" structname: "MockBazTwo" io: config: dir: path/to/io/mocks filename: "mocks_io.go" ``` -------------------------------- ### v2 Mockery Configuration Schema Source: https://vektra.github.io/mockery/latest-v3/v3 An example of a v2 mockery configuration file. This schema is used as input for the migration tool. ```yaml quiet: False disable-version-string: True with-expecter: True structname: "{{.InterfaceNameCamel}}" filename: "{{.StructName}}_mock.go" outpkg: mocks tags: "custom2" issue-845-fix: True resolve-type-alias: False packages: github.com/vektra/mockery/v2/pkg/fixtures: config: all: True interfaces: RequesterVariadic: config: with-expecter: False configs: - structname: RequesterVariadicOneArgument unroll-variadic: False - structname: RequesterVariadic unroll-variadic: True ReplaceGeneric: config: replace-type: - github.com/vektra/mockery/v2/pkg/fixtures.ReplaceGeneric[-TImport]=github.com/vektra/mockery/v2/pkg/fixtures/redefined_type_b.B - github.com/vektra/mockery/v2/pkg/fixtures.ReplaceGeneric[TConstraint]=github.com/vektra/mockery/v2/pkg/fixtures/constraints.String ``` -------------------------------- ### Mockery Configuration for Testify Source: https://vektra.github.io/mockery/latest-v3/template/testify Example YAML configuration for Mockery to generate Testify-compatible mocks. ```APIDOC ## Mockery Configuration This YAML configuration specifies the template to use (`testify`), the packages to process, and the desired output for generated mocks. ```yaml template: testify packages: github.com/vektra/mockery/v3/pkg/fixtures: config: dir: "{{.InterfaceDir}}" filename: "mocks.go" pkgname: "test" structname: "Mock{{.InterfaceName}}" interfaces: Requester: ``` ``` -------------------------------- ### Complex Mockery Configuration Example Source: https://vektra.github.io/mockery/latest-v3/configuration An advanced YAML configuration demonstrating various options like custom boilerplate, template data, and multiple configurations for a single interface. ```yaml all: False template-data: boilerplate-file: ./path/to/boilerplate.txt template: testify packages: github.com/vektra/example: config: # Make use of the template variables to place the mock in the same # directory as the original interface. dir: "{{.InterfaceDir}}" filename: "mocks_test.go" pkgname: "{{.PackageName}}_test" structname: "{{.Mock}}{{.InterfaceName}}" interfaces: Foo: Bar: config: # Make it unexported instead structname: "mock{{.InterfaceName}}" Baz: # Create two mock implementations of Baz with different names. configs: - filename: "mocks_baz_one_test.go" structname: "MockBazOne" - filename: "mocks_baz_two_test.go" structname: "MockBazTwo" io: config: dir: path/to/io/mocks filename: "mocks_io.go" ``` -------------------------------- ### Generated Mock Code Structure (Testify) Source: https://vektra.github.io/mockery/latest-v3/template/testify Example of the Go code generated by Mockery for a Testify mock, including interface definitions and mock methods. ```Go // Code generated by mockery; DO NOT EDIT. // github.com/vektra/mockery package test import ( mock "github.com/stretchr/testify/mock" ) // 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. // The first argument is typically a *testing.T value. func NewRequester (t interface { mock.TestingT Cleanup(func()) }) *Requester { // ... } // Requester is an autogenerated mock type for the Requester type type Requester struct { mock.Mock } type Requester_Expecter struct { mock *mock.Mock } func (_m *Requester) EXPECT() *Requester_Expecter { // ... } // Get provides a mock function for the type Requester func (_mock *Requester) Get(path string) (string, error) { // ... } // Requester_Get_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Get' type Requester_Get_Call struct { *mock.Call } // Get is a helper method to define mock.On call // - path func (_e *Requester_Expecter) Get(path interface{}, ) *Requester_Get_Call { // ... } func (_c *Requester_Get_Call) Run(run func(path string)) *Requester_Get_Call { // ... } func (_c *Requester_Get_Call) Return(s string, err error) *Requester_Get_Call { // ... } func (_c *Requester_Get_Call) RunAndReturn(run func(path string)(string, error)) *Requester_Get_Call { // ... } ``` -------------------------------- ### Basic Testify Mock Usage Source: https://vektra.github.io/mockery/latest-v3/template/testify Demonstrates a basic test case using a Mockery-generated mock with Testify. It sets an expectation for the Get method and asserts the returned values. ```Go package test import ( "testing" "github.com/stretchr/testify/assert" ) 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") } ``` -------------------------------- ### Function Using an Interface Source: https://vektra.github.io/mockery/latest-v3 This Go function accepts a DB interface and calls its Get method. ```go func getFromDB(db DB) string { return db.Get("ice cream") } ``` -------------------------------- ### Formatter Options for Goimports Source: https://vektra.github.io/mockery/latest-v3/configuration Example of configuring formatter options for goimports, including local prefix and tab indentation. This is used to customize how generated code is formatted. ```yaml --- formatter: goimports formatter-options: goimports: local-prefix: github.com/myrepo tab-indent: true ``` -------------------------------- ### Configure Mockery for External Packages Source: https://vektra.github.io/mockery/latest/faq Use this YAML configuration to generate mocks for external Go packages. Ensure the package is fetched with `go get` and specify recursive generation and output directory. ```yaml packages: go.temporal.io/sdk: config: all: true recursive: true dir: mocks/{{.SrcPackagePath}} filename: mocks.go ``` -------------------------------- ### Configure Mockery for External Packages Source: https://vektra.github.io/mockery/latest-v3/faq Use this YAML configuration to generate mocks for external Go packages. Ensure the external package is fetched using `go get` before configuring. ```yaml packages: go.temporal.io/sdk: config: all: true recursive: true dir: mocks/{{.SrcPackagePath}} filename: mocks.go ``` -------------------------------- ### Generated Mock Struct Source: https://vektra.github.io/mockery/latest-v3/generate-directive This is an example of an autogenerated mock struct for the `Requester` interface, named `MockFoo` as specified by the directive. ```go // MockFoo is an autogenerated mock type for the Requester type type MockFoo struct { mock.Mock } ``` -------------------------------- ### Mock with Qualified Type References Source: https://vektra.github.io/mockery/latest-v3/inpackage This example shows a mock generated when the output file resides outside the original package. It includes qualified type references like `inpackage.InternalStringType` and an import for the original package. ```go import ( mock "github.com/stretchr/testify/mock" "github.com/vektra/mockery/v3/internal/fixtures/inpackage" ) // Bar provides a mock function for the type MockFoo func (_mock *MockFoo) Bar() inpackage.InternalStringType { ``` -------------------------------- ### Define Requester Interface Source: https://vektra.github.io/mockery/latest-v3/template/matryer This Go code defines the Requester interface with a Get method. This interface will be used to generate mocks. ```Go package test type Requester interface { Get(path string) (string, error) } ``` -------------------------------- ### Enable Debug Logging in Mockery Source: https://vektra.github.io/mockery/latest-v3/faq Set `log-level: debug` in your Mockery configuration to get detailed logs. This can help diagnose issues like interfaces not being found. ```yaml log-level: debug ``` -------------------------------- ### Mockery v3 Config Template Function Change Source: https://vektra.github.io/mockery/latest-v3/v3 In Mockery v3, template function argument orders for functions taking input strings have been swapped to support template pipelines. This example shows the reordered `trimSuffix` function. ```go "trimSuffix": func(suffix string, s string) string { return strings.TrimSuffix(s, suffix) }, ``` -------------------------------- ### Initialize Mockery Configuration Source: https://vektra.github.io/mockery/latest-v3/configuration Use `mockery init` to bootstrap a new configuration file. This command generates a `.mockery.yml` file with default settings. ```bash $ mockery init github.com/vektra/mockery/v3/internal/fixtures 2025-03-14T23:06:12.535709000-05:00 INF writing to file file=.mockery.yml version=v0.0.0-dev 2025-03-14T23:06:12.536493000-05:00 INF done version=v0.0.0-dev ``` -------------------------------- ### Running Mockery Source: https://vektra.github.io/mockery/latest-v3 Command to run Mockery with configuration, showing its startup and generation process. ```bash $ mockery 05 Mar 23 21:49 CST INF Starting mockery dry-run=false version=v3.0.0 05 Mar 23 21:49 CST INF Using config: .mockery.yaml dry-run=false version=v3.0.0 05 Mar 23 21:49 CST INF Generating mock dry-run=false interface=DB qualified-name=github.com/org/repo version=v3.0.0 ``` -------------------------------- ### Run Mockery with Configuration Source: https://vektra.github.io/mockery/latest-v3/configuration Execute Mockery using the generated configuration file to generate mock code. The output shows the generation process. ```bash $ mockery 2025-03-14T23:42:17.014113000-05:00 INF Starting mockery config-file=/Users/landon/git/LandonTClipp/mockery/.mockery.yaml version=v0.0.0-dev 2025-03-14T23:42:17.014258000-05:00 INF Parsing configured packages... version=v0.0.0-dev 2025-03-14T23:42:17.527483000-05:00 INF Done parsing configured packages. version=v0.0.0-dev [...] 2025-03-14T23:42:17.531239000-05:00 INF Executing template file=/Users/landon/git/LandonTClipp/mockery/internal/fixtures/mocks_test.go version=v0.0.0-dev 2025-03-14T23:42:17.690601000-05:00 INF Writing template to file file=/Users/landon/git/LandonTClipp/mockery/internal/fixtures/mocks_test.go version=v0.0.0-dev ``` -------------------------------- ### Configuration Source Precedence Source: https://vektra.github.io/mockery/latest/configuration Illustrates how Mockery loads configuration values from different sources, prioritizing CLI parameters over environment variables and config files. ```text source | value ---|--- command line | --enable-feature=true Environment variable | MOCKERY_ENABLE_FEATURE=True yaml | enable-feature: True ``` -------------------------------- ### Define a Golang Interface Source: https://vektra.github.io/mockery/latest-v3 This Go code defines a simple interface named DB with a single method Get. ```go type DB interface { Get(val string) string } ``` -------------------------------- ### Mocking Multiple Calls with Testify Source: https://vektra.github.io/mockery/latest/template/testify Illustrates how to set up mocks to return different values on successive calls with identical arguments using .Once() or .Times(). ```go // Return "foo" on the first call gotter := NewGetter() assert(t, "foo", getter.Get("key")) // Return "bar" on the second call assert(t, "bar", getter.Get("key")) ``` ```go mockGetter := NewMockGetter(t) mockGetter.EXPECT().Get(mock.anything).Return("foo").Once() mockGetter.EXPECT().Get(mock.anything).Return("bar").Once() ``` ```go mockGetter := NewMockGetter(t) mockGetter.EXPECT().Get(mock.anything).Return("foo").Times(4) mockGetter.EXPECT().Get(mock.anything).Return("bar").Times(2) ``` -------------------------------- ### Run Mockery Migration Command Source: https://vektra.github.io/mockery/latest-v3/v3 Use the `mockery migrate` command to initiate the migration process to v3. This command helps in updating your existing mockery configurations and generating mocks according to the new v3 standards. ```bash mockery migrate ``` -------------------------------- ### Running the Mockery Migrate Command Source: https://vektra.github.io/mockery/latest-v3/v3 Command to execute the mockery migrate tool, specifying the v2 configuration file. The output indicates the migration process and any detected breaking changes. ```bash $ mockery migrate --config ./.mockery_v2.yml 2025-03-28T00:26:44.762164000-05:00 INF using config config=./.mockery_v2.yml version=v0.0.0-dev 2025-03-28T00:26:44.762804000-05:00 INF writing v3 config config=./.mockery_v2.yml v3-config=.mockery_v3.yml version=v0.0.0-dev 2025-03-28T00:26:44.762914000-05:00 WRN breaking changes detected that possibly require manual intervention. See table below. config=./.mockery_v2.yml version=v0.0.0-dev ``` -------------------------------- ### Run Mockery CLI Source: https://vektra.github.io/mockery/latest-v2 Command to execute Mockery with a specified configuration file to generate mocks. ```bash $ mockery 05 Mar 23 21:49 CST INF Starting mockery dry-run=false version=v2.20.0 05 Mar 23 21:49 CST INF Using config: .mockery.yaml dry-run=false version=v2.20.0 05 Mar 23 21:49 CST INF Walking dry-run=false version=v2.20.0 05 Mar 23 21:49 CST INF Generating mock dry-run=false interface=DB qualified-name=github.com/org/repo version=v2.20.0 ``` -------------------------------- ### Migrate v2 Config to v3 Source: https://vektra.github.io/mockery/latest/v3 Use the `mockery migrate` command to convert your v2 configuration file to the v3 schema. The tool outputs a new v3 config file and a deprecation table highlighting potential manual changes. ```yaml quiet: False disable-version-string: True with-expecter: True structname: "{{.InterfaceNameCamel}}" filename: "{{.StructName}}_mock.go" outpkg: mocks tags: "custom2" issue-845-fix: True resolve-type-alias: False packages: github.com/vektra/mockery/v2/pkg/fixtures: config: all: True interfaces: RequesterVariadic: config: with-expecter: False configs: - structname: RequesterVariadicOneArgument unroll-variadic: False - structname: RequesterVariadic unroll-variadic: True ReplaceGeneric: config: replace-type: - github.com/vektra/mockery/v2/pkg/fixtures.ReplaceGeneric[-TImport]=github.com/vektra/mockery/v2/pkg/fixtures/redefined_type_b.B - github.com/vektra/mockery/v2/pkg/fixtures.ReplaceGeneric[TConstraint]=github.com/vektra/mockery/v2/pkg/fixtures/constraints.String ``` ```bash $ mockery migrate --config ./.mockery_v2.yml 2025-03-28T00:26:44.762164000-05:00 INF using config config=./.mockery_v2.yml version=v0.0.0-dev 2025-03-28T00:26:44.762804000-05:00 INF writing v3 config config=./.mockery_v2.yml v3-config=.mockery_v3.yml version=v0.0.0-dev 2025-03-28T00:26:44.762914000-05:00 WRN breaking changes detected that possibly require manual intervention. See table below. config=./.mockery_v2.yml version=v0.0.0-dev ``` -------------------------------- ### Mockery Configuration for Testify Source: https://vektra.github.io/mockery/latest-v3/template/testify YAML configuration file for Mockery specifying the testify template and package details. ```YAML template: testify packages: github.com/vektra/mockery/v3/pkg/fixtures: config: dir: "{{.InterfaceDir}}" filename: "mocks.go" pkgname: "test" structname: "Mock{{.InterfaceName}}" interfaces: Requester: ``` -------------------------------- ### Mockery Configuration Source: https://vektra.github.io/mockery/latest-v3 A YAML configuration file for Mockery, specifying packages and interfaces to generate mocks for. ```yaml packages: github.com/org/repo: interfaces: DB: ``` -------------------------------- ### Generated Mock Code Structure (Testify) Source: https://vektra.github.io/mockery/latest-v3/template/testify Illustrates the structure of Go code generated by Mockery when using the Testify template. ```APIDOC ## Generated Mock Code This is an example of the Go code generated by Mockery for the `Requester` interface using the Testify template. It includes mock setup, expectation setting, and method mocking. ```go // Code generated by mockery; DO NOT EDIT. // github.com/vektra/mockery package test import ( mock "github.com/stretchr/testify/mock" ) // 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. // The first argument is typically a *testing.T value. func NewRequester (t interface { mock.TestingT; Cleanup(func()) }) *Requester { // ... } // Requester is an autogenerated mock type for the Requester type type Requester struct { mock.Mock } type Requester_Expecter struct { mock *mock.Mock } func (_m *Requester) EXPECT() *Requester_Expecter { // ... } // Get provides a mock function for the type Requester func (_mock *Requester) Get(path string) (string, error) { // ... } // Requester_Get_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Get' type Requester_Get_Call struct { *mock.Call } // Get is a helper method to define mock.On call // - path func (_e *Requester_Expecter) Get(path interface{}, ) *Requester_Get_Call { // ... } func (_c *Requester_Get_Call) Run(run func(path string)) *Requester_Get_Call { // ... } func (_c *Requester_Get_Call) Return(s string, err error) *Requester_Get_Call { // ... } func (_c *Requester_Get_Call) RunAndReturn(run func(path string)(string, error)) *Requester_Get_Call { // ... } ``` ``` -------------------------------- ### Mocking Multiple Calls with Identical Arguments (Once) Source: https://vektra.github.io/mockery/latest-v3/template/testify Sets up a mock to return a specific value for the first call and a different value for the second call, using `.Once()` for each expectation. ```Go mockGetter := NewMockGetter(t) mockGetter.EXPECT().Get(mock.anything).Return("foo").Once() mockGetter.EXPECT().Get(mock.anything).Return("bar").Once() ``` -------------------------------- ### Generated Mock File Header Source: https://vektra.github.io/mockery/latest-v3/configuration The beginning of a generated mock file, showing the package declaration and necessary imports. Note the use of `// Code generated by mockery; DO NOT EDIT.`. ```go // Code generated by mockery; DO NOT EDIT. // github.com/vektra/mockery package test import ( "encoding/json" "io" "net/http" "unsafe" mock "github.com/stretchr/testify/mock" http1 "github.com/vektra/mockery/v3/internal/fixtures/12345678/http" "github.com/vektra/mockery/v3/internal/fixtures/constraints" http0 "github.com/vektra/mockery/v3/internal/fixtures/http" test "github.com/vektra/mockery/v3/internal/fixtures/redefined_type_b" ) ``` -------------------------------- ### Mocking Variadic Arguments with Testify Source: https://vektra.github.io/mockery/latest/template/testify Demonstrates asserting specific variadic arguments. Use mock.Anything for any number of arguments, or specify arguments explicitly. ```go func TestFoo(t *testing.T) { m := NewMockFoo(t) m.On("Bar", "hello", "world").Return(nil) ``` ```go m.On("Bar", mock.Anything).Return(nil) ``` ```go m.On("Bar", mock.Anything).Return(nil) ``` ```go m.On("Bar", mock.Anything).Return(nil) ``` ```go // case 1 m.On("Bar", mock.Anything).Return(nil) // case 2 m.On("Bar", []interface{}{mock.Anything}).Return(nil) ``` -------------------------------- ### Testify Template Configuration Options Source: https://vektra.github.io/mockery/latest-v3/template/testify Details the configuration options available for the Testify template in Mockery. ```APIDOC ## Testify Template Options The Testify template for Mockery supports the following configuration options: ### `template-data` | Key | Type | Description | |--------------------|--------|-------------------------------------------------------------------------------------------------------------------------------------------| | `boilerplate-file` | `string` | 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` | `string` | Set the build tags of the generated mocks. Read more about the format. | | `unroll-variadic` | `bool` | If set to `unroll-variadic: true`, will expand the variadic argument to testify using the `...` syntax. See notes for more details. | ### Schema ```json { "$schema": "http://json-schema.org/draft-07/schema#", "title": "vektra/mockery testify mock", "type": "object", "additionalProperties": false, "properties": { "boilerplate-file": { "type": "string" }, "mock-build-tags": { "type": "string" }, "unroll-variadic": { "type": "boolean" } }, "required": [] } ``` ``` -------------------------------- ### Requester Interface and Mock Usage Source: https://vektra.github.io/mockery/latest-v3/template/testify Defines a Go interface 'Requester' and demonstrates how to generate and use a mock implementation with Testify. ```APIDOC ## Requester Interface This Go interface defines a contract for making requests. ```go package test type Requester interface { Get(path string) (string, error) } ``` ## Mocking the Requester Interface with Testify This example shows how to use the generated mock for the `Requester` interface in a test. ```go package test import ( "testing" "github.com/stretchr/testify/assert" ) 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") } ``` ``` -------------------------------- ### Mock with Side Effect and Return using RunAndReturn Source: https://vektra.github.io/mockery/latest-v3/template/testify Shows how to use `RunAndReturn` to perform a side effect and return custom values from a mock method. The returned string is a concatenation of the input path and ' world'. ```Go func TestRequesterMockRunAndReturn(t *testing.T) { m := NewMockRequester(t) m.EXPECT().Get(mock.Anything).RunAndReturn(func(path string) (string, error) { return path + " world", nil }) retString, err := m.Get("hello") assert.NoError(t, err) assert.Equal(t, retString, "hello world") } ``` -------------------------------- ### Expecter Struct with RunAndReturn for Dynamic Return Values Source: https://vektra.github.io/mockery/latest/template/testify Demonstrates using the `RunAndReturn` method on an expecter struct to dynamically set return values based on mock call inputs. ```Go requesterMock.EXPECT(). Get(mock.Anything). RunAndReturn(func(path string) (string, error) { fmt.Println(path, "was called") return ("result for " + path), nil }) ``` -------------------------------- ### Mocking Variadic Arguments with Testify (Future) Source: https://vektra.github.io/mockery/latest-v3/template/testify Demonstrates how variadic arguments could be mocked if a Testify patch is merged, allowing explicit control over argument matching. ```Go // case 1 m.On("Bar", mock.Anything).Return(nil) // case 2 m.On("Bar", []interface{}{mock.Anything}).Return(nil) ``` -------------------------------- ### Mocking Multiple Calls with Identical Arguments (Times) Source: https://vektra.github.io/mockery/latest-v3/template/testify Sets up a mock to return specific values for a defined number of calls using `.Times()` for each expectation. ```Go mockGetter := NewMockGetter(t) mockGetter.EXPECT().Get(mock.anything).Return("foo").Times(4) mockGetter.EXPECT().Get(mock.anything).Return("bar").Times(2) ``` -------------------------------- ### Using RunAndReturn() for Side Effects and Return Values Source: https://vektra.github.io/mockery/latest-v3/template/testify Shows how to use `RunAndReturn()` to execute a function that also returns values, useful for complex mock behavior. ```APIDOC ## Custom Return Logic with `RunAndReturn()` `RunAndReturn()` executes a function and returns its results, providing flexibility for mock behavior. ```go func TestRequesterMockRunAndReturn(t *testing.T) { m := NewMockRequester(t) m.EXPECT().Get(mock.Anything).RunAndReturn(func(path string) (string, error) { return path + " world", nil }) retString, err := m.Get("hello") assert.NoError(t, err) assert.Equal(t, retString, "hello world") } ``` ``` -------------------------------- ### Translated v3 Config Source: https://vektra.github.io/mockery/latest/v3 The output of the `mockery migrate` command includes the translated v3 configuration file in YAML format. ```yaml structname: '{{.InterfaceNameCamel}}' pkname: mocks template: testify template-data: with-expecter: true packages: github.com/vektra/mockery/v2/pkg/fixtures: config: all: true interfaces: ReplaceGeneric: config: {} RequesterVariadic: config: template-data: with-expecter: false configs: - structname: RequesterVariadicOneArgument template-data: unroll-variadic: false - structname: RequesterVariadic template-data: unroll-variadic: true ``` -------------------------------- ### Test Using a Mock Object Source: https://vektra.github.io/mockery/latest-v3 A Go test function demonstrating how to use a generated mock object (NewMockDB) and its EXPECT method for assertions. ```go import ( "testing" "github.com/stretchr/testify/assert" ) func Test_getFromDB(t *testing.T) { mockDB := NewMockDB(t) mockDB.EXPECT().Get("ice cream").Return("chocolate").Once() flavor := getFromDB(mockDB) assert.Equal(t, "chocolate", flavor) } ``` -------------------------------- ### Specify Local File Template Source: https://vektra.github.io/mockery/latest-v3/template Use the 'file://' protocol to specify a local template file. The path can be relative or absolute. ```yaml template: "file://" ``` -------------------------------- ### Enable Mock Generation for an Interface Source: https://vektra.github.io/mockery/latest-v3/generate-directive Use the `//mockery:generate: true` directive within an interface's doc comment to explicitly enable mock generation for that interface. This is useful when the global configuration has `all: false`. ```go package directivecommentsexample // Requester is an interface that defines a method for making HTTP requests. // //mockery:generate: true type Requester interface { Get(path string) (string, error) } ``` -------------------------------- ### Pull Mockery Docker Image Source: https://vektra.github.io/mockery/latest-v3/installation Download the official Mockery Docker image for use in containerized environments. ```bash docker pull vektra/mockery ``` -------------------------------- ### Using Run() for Side Effects Source: https://vektra.github.io/mockery/latest-v3/template/testify Demonstrates how to use the `Run()` method on mock expectations to execute custom logic when a mock method is called. ```APIDOC ## Side Effects with `Run()` The `Run()` method allows you to execute a function when a mock method is called, enabling side effects. ```go func TestRequesterMockRun(t *testing.T) { m := NewMockRequester(t) m.EXPECT().Get(mock.Anything).Return("", nil) m.EXPECT().Get(mock.Anything).Run(func(path string) { fmt.Printf("Side effect! Argument is: %s", path) }) retString, err := m.Get("hello") assert.NoError(t, err) assert.Equal(t, retString, "") } ``` ``` -------------------------------- ### Mocking with Embedded Testify Mock Object Source: https://vektra.github.io/mockery/latest-v3/template/testify Illustrates how to interact with the embedded `mock.Mock` object directly, allowing the use of Testify's built-in methods like `Calls` to inspect mock interactions. ```Go func TestRequesterMockTestifyEmbed(t *testing.T) { m := NewMockRequester(t) m.EXPECT().Get(mock.Anything).Return("", nil).Twice() m.Get("hello") m.Get("world") assert.Equal(t, len(m.Mock.Calls), 2) } ``` -------------------------------- ### Mock with Unqualified Type References (`inpackage: true`) Source: https://vektra.github.io/mockery/latest-v3/inpackage When `inpackage: true` is set, this is the resulting mock code. The import for the original package is removed, and types are referred to by their unqualified names, such as `InternalStringType`. ```go import ( mock "github.com/stretchr/testify/mock" ) // Bar provides a mock function for the type MockFoo func (_mock *MockFoo) Bar() InternalStringType { ``` -------------------------------- ### Generate Mocks using Docker Source: https://vektra.github.io/mockery/latest-v3/installation Run Mockery within a Docker container, mounting the current directory as a volume for processing project files. ```bash docker run -v "$PWD":/src -w /src vektra/mockery:3 ``` -------------------------------- ### Return Value Provider - Single Function Source: https://vektra.github.io/mockery/latest-v3/template/testify Use a single function with the exact signature of the mocked method to provide return values. This is useful for dynamic return logic. ```Go type Proxy interface { passthrough(ctx context.Context, s string) (string, error) } ``` ```Go proxyMock := mocks.NewProxy(t) proxyMock.On("passthrough", mock.AnythingOfType("context.Context"), mock.AnythingOfType("string")). Return( func(ctx context.Context, s string) (string, error) { return s, nil } ) ``` -------------------------------- ### Mock Requester Usage with Matryer Source: https://vektra.github.io/mockery/latest-v3/template/matryer This Go code demonstrates how to use a matryer-style mock for the Requester interface in a test. It configures the GetFunc to provide custom behavior and asserts the results. ```Go func TestRequesterMoq(t *testing.T) { m := &MoqRequester{ GetFunc: func(path string) (string, error) { fmt.Printf("Go path: %s\n", path) return path + "/foo", nil }, } result, err := m.Get("/path") assert.NoError(t, err) assert.Equal(t, "/path/foo", result) } ``` -------------------------------- ### Return Value Provider - Multiple Functions Source: https://vektra.github.io/mockery/latest-v3/template/testify Provide separate functions for each return parameter of the mocked function. This allows defining individual return values for each output. ```Go proxyMock := mocks.NewProxy(t) proxyMock.On("passthrough", mock.AnythingOfType("context.Context"), mock.AnythingOfType("string")). Return( func(ctx context.Context, s string) string { return s }, func(ctx context.Context, s string) error { return nil }, ) ``` -------------------------------- ### Original Mock Function Signature (Before Replacement) Source: https://vektra.github.io/mockery/latest-v3/replace-type This Go code snippet shows the signature of a mock function before the `replace-type:` configuration is applied. It reflects the original interface definition. ```go // Replace2 provides a mock function for the type RTypeReplaced1 func (_mock *RTypeReplaced1) Replace1(f rt1.RType1) { _mock.Called(f) return } ``` -------------------------------- ### Using Expecter Structs for Type-Safe Mock Expectations Source: https://vektra.github.io/mockery/latest/template/testify Illustrates how to use the expecter struct feature in Mockery for type-safe method call expectations on mock objects. ```Go type Requester interface { Get(path string) (string, error) } requesterMock := mocks.NewRequester(t) requesterMock.EXPECT().Get("some path").Return("result", nil) ``` -------------------------------- ### Migrated v3 Mockery Configuration Schema Source: https://vektra.github.io/mockery/latest-v3/v3 The resulting v3 mockery configuration file generated by the migrate tool. This schema reflects the updated structure and options for mockery v3. ```yaml structname: '{{.InterfaceNameCamel}}' pkgname: mocks template: testify template-data: with-expecter: true packages: github.com/vektra/mockery/v2/pkg/fixtures: config: all: true interfaces: ReplaceGeneric: config: {} RequesterVariadic: config: template-data: with-expecter: false configs: - structname: RequesterVariadicOneArgument template-data: unroll-variadic: false - structname: RequesterVariadic template-data: unroll-variadic: true ``` -------------------------------- ### Matryer Mockery Configuration Source: https://vektra.github.io/mockery/latest-v3/template/matryer This YAML configuration specifies the use of the 'matryer' template for generating mocks. It defines the output package, filename, struct name, and the interfaces to mock for a specific Go package. ```YAML template: matryer packages: github.com/vektra/mockery/v3/pkg/fixtures: config: dir: "{{.InterfaceDir}}" filename: "mocks_moq.go" pkgname: "test" structname: "Moq{{.InterfaceName}}" interfaces: Requester: ``` -------------------------------- ### Remote Template Configuration Source: https://vektra.github.io/mockery/latest/template Configure Mockery to use a remote template hosted on GitHub, specifying both the template and its schema. ```yaml template: https://raw.githubusercontent.com/vektra/mockery/refs/tags/v3.0.0-beta.8/e2e/test_template_exercise/exercise.templ template-schema: https://raw.githubusercontent.com/vektra/mockery/refs/tags/v3.0.0-beta.8/e2e/test_template_exercise/exercise.templ.schema.json ``` -------------------------------- ### Generate Mocks for Interfaces in Main Package Source: https://vektra.github.io/mockery/latest/faq When mocking interfaces defined in the `main` package, use the `--inpackage` flag. This flag ensures mocks are generated within the same package, preventing import conflicts. ```bash mockery --inpackage ``` -------------------------------- ### Specify Testify Template Source: https://vektra.github.io/mockery/latest-v3/template Use the 'testify' template to generate powerful, testify-based mock objects with argument-to-return-value matching. ```yaml template: "testify" ``` -------------------------------- ### Generated Matryer Mock Structure Source: https://vektra.github.io/mockery/latest-v3/template/matryer This Go code shows the structure of a mock generated using the matryer template. It includes the mock struct definition, method mocks (e.g., GetFunc), and methods for tracking calls. ```Go // Code generated by mockery; DO NOT EDIT. // github.com/vektra/mockery package test import ( "sync" ) // Ensure, that MoqRequester does implement Requester. // If this is not the case, regenerate this file with moq. var _ Requester = &MoqRequester{} // MoqRequester is a mock implementation of Requester. // // func TestSomethingThatUsesRequester(t *testing.T) { // // // make and configure a mocked Requester // mockedRequester := &MoqRequester{ // GetFunc: func(path string) (string, error) { // panic("mock out the Get method") // }, // } // // // use mockedRequester in code that requires Requester // // and then make assertions. // // } type MoqRequester struct { // GetFunc mocks the Get method. GetFunc func(path string) (string, error) // calls tracks calls to the methods. calls struct { // Get holds details about calls to the Get method. Get []struct { // Path is the path argument value. Path string } } lockGet sync.RWMutex } // Get calls GetFunc. func (mock *MoqRequester) Get(path string) (string, error) { // ... } // GetCalls gets all the calls that were made to Get. // Check the length with: // // len(mockedRequester.GetCalls()) func (mock *MoqRequester) GetCalls() []struct { Path string } { // ... } ``` -------------------------------- ### Mockery Configuration for Type Replacement Source: https://vektra.github.io/mockery/latest-v3/replace-type The `.mockery.yml` configuration specifies that `rt1.RType1` should be replaced with `rt2.RType2` from a different package path. This allows mocking of types that might be internal or difficult to access directly. ```yaml replace-type: github.com/vektra/mockery/v3/internal/fixtures/example_project/replace_type/rti/rt1: RType1: pkg-path: github.com/vektra/mockery/v3/internal/fixtures/example_project/replace_type/rti/rt2 type-name: RType2 ``` -------------------------------- ### Mockery Testify Template Configuration Schema Source: https://vektra.github.io/mockery/latest/template/testify The JSON schema defining the configuration options for Mockery when using the Testify template. It includes properties like boilerplate-file, mock-build-tags, and unroll-variadic. ```json { "$schema": "http://json-schema.org/draft-07/schema#", "title": "vektra/mockery testify mock", "type": "object", "additionalProperties": false, "properties": { "boilerplate-file": { "type": "string" }, "mock-build-tags": { "type": "string" }, "unroll-variadic": { "type": "boolean" } }, "required": [] } ``` -------------------------------- ### Mocking Any Number of Variadic Arguments (Ambiguous) Source: https://vektra.github.io/mockery/latest-v3/template/testify This assertion is ambiguous and may not behave as expected. It attempts to match any number of variadic arguments. ```Go m.On("Bar", mock.Anything).Return(nil) ```