Skip to content

mockery

Mockery is a project that creates mock implementations of Golang interfaces. The mocks generated in this project are based off of the github.com/stretchr/testify suite of testing packages.

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
with-expecter: True
packages:
    github.com/org/repo:
        interfaces:
            DB:
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

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 over gomock?

  1. mockery provides a much more user-friendly API and is less confusing to use
  2. mockery utilizes testify which is a robust and highly feature-rich testing framework
  3. mockery has rich configuration options that allow fine-grained control over how your mocks are generated
  4. mockery's CLI is more robust, user-friendly, and provides many more options
  5. mockery supports generics (this may no longer be an advantage if/when gomock supports generics)

Who uses mockery?

Get Started