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
go get -tool go.uber.org/mock/mockgenOld method
go install go.uber.org/mock/mockgen@latestCheck version for verify installation.
go tool mockgen -version
# mockgen --versionOld method to add makefile
Add this installation in the Makefile for easy access.
.PHONY: tools
tools: ## Download tools (mockgen)
go install go.uber.org/mock/mockgen@latestIf 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:generate go tool mockgen -source=${GOFILE} -destination=mock_test.go -package=${GOPACKAGE} ConfigLoaderEnd of mockgen command, you need to add which interfaces you want to generate mock. Proper example for generate mock in interface.go file:
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.
ctrl := gomock.NewController(t)
defer ctrl.Finish()
clMock := NewMockConfigLoader(ctrl)After that use that clMock to add EXPECT and returns, for example:
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)