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 install go.uber.org/mock/mockgen@latest
Check version for verify installation.
mockgen --version
Add this installation in the Makefile
for easy access.
.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:generate mockgen -source=${GOFILE} -destination=interface_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:
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)