Skip to content

Mock Interfaces ​

Mock package in golang https://github.com/uber-go/mock

Google mock repo maintaining by Uber, it is new version of golang/mock.

Install ​

sh
go get -tool go.uber.org/mock/mockgen
Old method
sh
go install go.uber.org/mock/mockgen@latest

Check version for verify installation.

sh
go tool mockgen -version
# mockgen --version
Old method to add makefile

Add this installation in the Makefile for easy access.

makefile
.PHONY: tools
tools: ## Download tools (mockgen)
	go install go.uber.org/mock/mockgen@latest

If you editing the interface and creating new mock, please use always last version of mockgen.

Generate Mock ​

If you have interface like below or you could be have multiple interfaces in the same file.

go
//go:generate go tool mockgen -source=${GOFILE} -destination=mock_test.go -package=${GOPACKAGE} ConfigLoader

End of mockgen command, you need to add which interfaces you want to generate mock. Proper example for generate mock in interface.go file:

go
package etl

import (
	"context"

	"xxx/models"
)

//go:generate mockgen -source=${GOFILE} -destination=interface_test.go -package=${GOPACKAGE} Loader

type Loader interface {
	GetConfig(ctx context.Context, id int) (*models.Data, error)
	SetConfig(ctx context.Context, data []byte) (error)
}

Just click generate command in the IDE to run it. It will generate interface_test.go file in the same directory.

Don't generate mock in the common mock folder, every component should be isolated in the same directory!

Usage ​

First create mock of the sturct, code generated by mockgen and just reach NewMockXXX function.

go
ctrl := gomock.NewController(t)
defer ctrl.Finish()

clMock := NewMockConfigLoader(ctrl)

After that use that clMock to add EXPECT and returns, for example:

go
cl.EXPECT().GetFileType(gomock.Any(), gomock.Any()).Return(&models.Data{
    Test: 2,
}, nil).Times(1)

cl.EXPECT().GetPluginType(gomock.Any(), 2).Return(nil, errors.New("meaningless error")).Times(1)