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:
and a function that takes this interface:
We can use simple configuration to generate a mock implementation for the interface:
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?¶
- mockery provides a much more user-friendly API and is less confusing to use
- mockery utilizes
testify
which is a robust and highly feature-rich testing framework - mockery has rich configuration options that allow fine-grained control over how your mocks are generated
- mockery's CLI is more robust, user-friendly, and provides many more options
- mockery supports generics (this may no longer be an advantage if/when gomock supports generics)