mock
is a code generation tool meant to be used withgo generate
. Itgenerates simple mock implementations of interfaces for use in testing.
Mocks are thread-safe.
You can installmock
locally using...
go install github.com/nicheinc/mock
...or just usego:generate go run github.com/nicheinc/mock@main
tohave thego generate
command automatically use the latest version (see belowfor example usage).
The only required argument tomock
is the name of the interface to mock,which must be provided after all other flags:
Usage: mock [options] interfaceOptions: -d string Directory to search for interface in (default ".") -o string Output file (default stdout)
Given this interface:
package maintypeGetterinterface {GetByID(idint) ([]string,error)GetByName(namestring) ([]string,error)}
mock Getter
will generate an implementation like this, and print it tostdout:
package main// GetterMock is a mock implementation of the Getter// interface.typeGetterMockstruct {GetByIDStubfunc(idint) ([]string,error)GetByIDCalledint32GetByNameStubfunc(namestring) ([]string,error)GetByNameCalledint32}var_Getter=&GetterMock{}// GetByID is a stub for the Getter.GetByID// method that records the number of times it has been called.func (m*GetterMock)GetByID(idint) ([]string,error) {atomic.AddInt32(m.GetByIDCalled,1)returnm.GetByIDStub(id)}// GetByName is a stub for the Getter.GetByName// method that records the number of times it has been called.func (m*GetterMock)GetByName(namestring) ([]string,error) {atomic.AddInt32(m.GetByNameCalled,1)returnm.GetByNameStub(name)}
To use withgo generate
, simply place ago:generate
comment somewhere inyour package (e.g. above the interface definition), like so:
//go:generate go run github.com/nicheinc/mock@main -o getter_mock.go Getter
Note the use of the-o
flag, which specifies the output file. If this flagis not provided, the mocked implementation will be printed to stdout.
Then run thego generate
command from the package directory.
Voila! There should now be agetter_mock.go
file containing your new mock, inthe same package as the interface definition. Subsequent runs ofgo generate
will overwrite the file, so be careful not to edit it!