mockery Documentation

repository·v3·Indexed 27 days ago

https://github.com/vektra/mockery

A high-performance code generation tool for Go that creates mock implementations of interfaces using the testify/mock framework. It features centralized YAML configuration via .mockery.yml, support for custom Go templates, and the ability to use //mockery:generate directives in source code to reduce manual boilerplate in unit tests.

Tokens
8.8K
Snippets
26
Records
65
Agent score
92%

What's inside mockery

  1. Overview of mockery

    v3
    mockery is a tool that automatically generates mocks for Golang interfaces. It uses the stretchr/testify/mock package to eliminate the boilerplate code typically required when writing mocks for unit tests.
  2. Overview of mockery features

    v3

    Mockery is a high-performance code-generation framework for Go. Key features include:

    • Multiple Mock Styles: Supports traditional mockery-style mocks and community styles like moq.
    • High Performance: Optimized for large codebases, making it significantly faster than many other Go code-generation tools.
    • YAML Configuration: Uses a centralized .mockery.yaml file instead of scattered //go:generate comments.
    • Custom Templates: Users can provide their own Go templates to generate any type of code based on interface information.
  3. Migrate from v2 to v3 using `mockery migrate`

    v3

    Mockery provides a migration tool to convert v2 configuration files to the v3 schema on a best-effort basis.

    Run the command pointing to your existing v2 YAML configuration. The tool will generate a new .mockery_v3.yml file and output a deprecation table in the terminal highlighting manual interventions required (such as changes to replace-type schema or template variable renames).

    Note: This tool is not comprehensive and may miss edge cases.

    $ mockery migrate --config ./.mockery_v2.yml
  4. Generate mocks for external packages

    v3

    To generate mocks for external packages, first ensure the package is available in your project using go get. Then, include the external package path in your mockery configuration.

    Example configuration for a Temporal SDK package:

    packages:
      go.temporal.io/sdk:
        config:
          all: true
          recursive: true
          dir: mocks/{{.SrcPackagePath}}
          filename: mocks.go
  5. Use `#!yaml inpackage:` to control mock package detection

    v3

    The #!yaml inpackage: parameter allows you to override mockery's automatic detection of whether a generated mock file resides inside or outside the original interface's package.

    By default, if mockery detects the mock is outside the original package, it adds import statements and uses qualified type names (e.g., pkg.TypeName). Setting #!yaml inpackage: true forces mockery to treat the mock as being inside the same package, which removes the extra import and uses the unqualified type name (e.g., TypeName).

    #!yaml inpackage: true
  6. Install mockery using Docker

    v3

    You can pull the mockery image from Docker Hub and run it to generate mocks for your project by mounting your current directory.

    docker pull vektra/mockery
    
    # Generate all mocks for your project
    docker run -v "$PWD":/src -w /src vektra/mockery:3
  7. Use Mock Constructors for automatic setup

    v3

    Mockery generates constructor functions (e.g., NewMockRequester(t)) that simplify test setup. These constructors automatically:

    • Register AssertExpectations to be called via t.Cleanup() at the end of the test.
    • Register the testing.TB interface on the mock.Mock object to prevent panics when unexpected calls occur.
    func TestRequesterMock(t *testing.T) {
        m := NewMockRequester(t)
        m.EXPECT().Get("foo").Return("bar", nil).Once()
        
        retString, err := m.Get("foo")
        assert.NoError(t, err)
        assert.Equal(t, retString, "bar")
    }
  8. Migrate from Mockery v2 to v3 parameters

    v3

    When upgrading to Mockery v3, several configuration parameters have changed or been removed. Use the following mapping to update your configuration:

    v2 Parameterv3 Status / Change
    inpackageRemoved. Mockery now automatically detects if a mock is in the same package.
    keeptreeRemoved. This parameter is no longer used.
    with-expecterRemoved. testify-style mocks now always generate expecter methods.
    excludeRenamed to exclude-subpkg-regex.
    unroll-variadicMoved. Now must be passed under the template-data map.
    resolve-type-aliasChanged. Now defaults to False (was True in v2).
    replace-typeUpdated. The schema is now more explicit compared to the v2 string list format.
  9. Use the `//mockery:generate` directive to configure mocks in source code

    v3

    Instead of using a central configuration file, you can use the //mockery:generate directive within Go doc comments to control mock generation for specific interfaces. This allows you to override configuration directly at the source of the interface.

    To enable generation for a specific interface, add //mockery:generate: true to its doc comments. If you have set all: false in your .mockery.yml configuration, this directive will opt that specific interface into the generation process.

    // Requester is an interface that defines a method for making HTTP requests.
    //
    //mockery:generate: true
    type Requester interface {
    	Get(path string) (string, error)
    }
  10. Generate Go interface mocks with mockery

    v3

    Mockery automates the creation of mock implementations for Golang interfaces. It inspects your source code and generates implementations that allow you to define behavior (expectations) during testing.

    To generate mocks, you can use a .mockery.yaml configuration file to specify the packages and interfaces you want to mock. This is preferred over using multiple //go:generate commands as it provides a centralized and flexible configuration scheme.

    packages:
    	github.com/org/repo:
    		interfaces:
    			DB:
  11. Replace types in generated mocks using `replace-type`

    v3

    The replace-type configuration parameter in .mockery.yml allows you to substitute a specific type in a generated mock with a different type. This is particularly useful when you need to work around packages that use internal types that are not accessible or desired in your test environment.

    To use this, define a mapping in your .mockery.yml where the key is the full package path of the type you want to replace, and the value is a map containing the specific type name and its replacement details (pkg-path and type-name).