GoMock is a mocking framework for the Go programming language. It integrates well with Go's built-in
testingpackage, but can be used in other contexts too.
Run these commands to install the
gomock package and the
go get github.com/golang/mock/gomock go get github.com/golang/mock/mockgen
Four steps of GoMock usage:
mockgento generate a mock for the interface you wish to mock.
- In your test, create an instance of
gomock.Controllerand pass it to your mock object’s constructor to obtain a mock object.
EXPECT()on your mocks to set up their expectations and return values
Finish()on the mock controller to assert the mock’s expectations
mockgen has two modes of operation: source and reflect. Source mode generates mock interfaces from a source file. It is enabled by using the -source flag. Other flags that may be useful in this mode are -imports and -aux_files.
mockgen -source=foo.go [other options]
Reflect mode generates mock interfaces by building a program that uses reflection to understand interfaces. It is enabled by passing two non-flag arguments: an import path, and a comma-separated list of symbols.
mockgen database/sql/driver Conn,Driver
Learn more at GiHub and with tutorial.