Generating Mock Objects With mockgen

To use GoMock, we need to install the code-generating tool mockgen first:

GO111MODULE=on go get github.com/golang/mock/mockgen@latest

mockgen will be installed into $GOPATH/bin . Then we can invoke this command to generate mock objects.

Note: mockgen support two modes of generation, source and reflect. We suggest you always using reflect mode since it is more powerful and can avoid some corner case of source mode.

Let’s say we have an interface Foo and a method Bar using it.

To generate mocking codes:

mockgen -destination=mocks/mock_foo.go -package=mocks . Foo

The command above finds the interface Foo in the current package (which is specified by the dot argument) and generates a mocking object for the interface.

Note: mockgen can be integrated with go:genernate. It helps us to keep the mockgen command near the interface to be mocked. Therefore, we can always put go:generate in the source file, like this:

The generated source codes are written to mocks/mock_foo.go (specified by the flag -destination ) and the target package is mocks (specified by the flag -package ).

The result looks like this:

MockFoo is the mocking object, and it implements the interface Foo . Every mocking object has a method EXPECT that returns a MockRecorder instance (in this case, MockFooMockRecorder ).

MockFooMockRecorder has all the methods of the interface Foo . The only difference is that the type of method parameter is interface{} .

NewMockFoo is a public function to create the mock instance.