Skip to content

mockery

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.

Why mockery?

When you have an interface like this:

db.go
type DB interface {
    Get(val string) string
}

and a function that takes this interface:

db_getter.go
func getFromDB(db DB) string {
    return db.Get("ice cream")
}

We can use simple configuration to generate a mock implementation for the interface:

.mockery.yaml
packages:
    github.com/org/repo:
        interfaces:
            DB:
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

We can then use the mock object in a test:

db_getter_test.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)
}

Why use mockery?

  1. 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.
  2. 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.
  3. Mockery provides a comprehensive, centralized, flexible, and simple configuration scheme driven off of yaml instead of relying on sprawling //go:generate commands.
  4. 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.
  5. A number of high profile companies, projects, and communities trust Mockery.

Who uses mockery?

Get Started