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:
and a function that takes this interface:
We can use simple configuration to generate a mock implementation for the interface:
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?¶
- 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.