mockery for Go: Complete Guide with Examples

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

mockery for Go: Complete Guide with Examples

\n\n

1. What It Is and Why You Need It

\n\n

Mockery is a powerful tool for generating mock objects in the Go language. In modern Go development, where interfaces play a key role, testing isolated components often requires creating stubs for external dependencies. Mockery automates this process by generating full interface implementations that can be used in unit tests. Instead of manually writing dozens of lines of code for each interface, you simply run one command and get a ready-made mock with all the necessary methods.

\n\n

The main purpose of mockery is to simplify testing code that depends on external services (databases, APIs, file systems, etc.). Generated mocks allow you to control return values, verify the number of method calls, and the arguments with which they were called. This is especially useful when developing microservices, where each component must be tested in isolation. The library uses the popular testify/mock package as its foundation, ensuring compatibility with most Go projects.

\n\n

Mockery supports both simple interfaces with a few methods and complex hierarchies. It can generate mocks for built-in types, interfaces from third-party packages, and even generic interfaces (starting with Go 1.18). Thanks to a flexible configuration system, you can control file names, the packages where mocks are placed, and even add custom methods. This makes mockery an indispensable tool in the arsenal of any Go developer striving for high-quality and maintainable code.

\n\n

2. Installation

\n\n

Installing mockery is done through the standard Go package manager. To do this, run the command:

\n\n
go install github.com/vektra/mockery/v2@latest
\n\n

After installation, make sure the binary file is in your $PATH. It is usually installed in $GOPATH/bin or $HOME/go/bin. You can verify the installation with the command:

\n\n
mockery --version
\n\n

If you are using Go modules, it is recommended to add mockery as a development tool. To do this, create or edit the tools.go file in the project root:

\n\n
//go:build tools\n// +build tools\n\npackage tools\n\nimport (\n    _ "github.com/vektra/mockery/v2"\n)\n
\n\n

Then run:

\n\n
go mod tidy
\n\n

This ensures that the mockery version will be pinned in your go.mod file.

\n\n

3. Quick Start — Minimal Working Example

\n\n

Let's look at a simple example. Suppose we have an interface UserRepository:

\n\n
// user.go\npackage main\n\ntype User struct {\n    ID   int\n    Name string\n}\n\ntype UserRepository interface {\n    GetUser(id int) (*User, error)\n    SaveUser(user *User) error\n}\n
\n\n

To generate the mock, run the command in the project root:

\n\n
mockery --name=UserRepository --output=mocks --with-expecter
\n\n

This command will create the file mocks/UserRepository.go with the mock implementation. Now we can use it in a test:

\n\n
// user_test.go\npackage main\n\nimport (\n    "testing"\n    "github.com/stretchr/testify/assert"\n    "your-project/mocks"\n)\n\nfunc TestGetUser(t *testing.T) {\n    // Create a mock\n    mockRepo := mocks.NewUserRepository(t)\n    \n    // Set up expected behavior\n    expectedUser := &User{ID: 1, Name: "Alice"}\n    mockRepo.On("GetUser", 1).Return(expectedUser, nil)\n    \n    // Call the function under test\n    user, err := mockRepo.GetUser(1)\n    \n    // Check the results\n    assert.NoErr                    

Recommendations