- Notifications
You must be signed in to change notification settings - Fork0
GoMock is a mocking framework for the Go programming language.
License
bjohnson-va/mock
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
gomock is a mocking framework for theGo programming language. Itintegrates well with Go's built-intesting
package, but can be used in othercontexts too.
This project originates from Google'sgolang/mock
repo. Unfortunately Googleno longer maintains this project, and given the heavy usage of gomock projectwithin Uber, we've decided to fork and maintain this going forward at Uber.
Contributions are welcome in the form of GitHub issue or PR!
This project is still WIP. We will be tagging a release shortly, in early July.
go.uber.org/mock supports all Go versions supported by the officialGo Release Policy. That is,the two most recent releases of Go.
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 thatmay be useful in this mode are -imports and -aux_files.
Example:
mockgen -source=foo.go [other options]
Reflect mode generates mock interfaces by building a programthat uses reflection to understand interfaces. It is enabledby passing two non-flag arguments: an import path, and acomma-separated list of symbols.
You can use "." to refer to the current path's package.
Example:
mockgen database/sql/driver Conn,Driver# Convenient for `go:generate`.mockgen. Conn,Driver
Themockgen
command is used to generate source code for a mockclass given a Go source file containing interfaces to be mocked.It supports the following flags:
-source
: A file containing interfaces to be mocked.-destination
: A file to which to write the resulting source code. If youdon't set this, the code is printed to standard output.-package
: The package to use for the resulting mock classsource code. If you don't set this, the package name ismock_
concatenatedwith the package of the input file.-imports
: A list of explicit imports that should be used in the resultingsource code, specified as a comma-separated list of elements of the formfoo=bar/baz
, wherebar/baz
is the package being imported andfoo
isthe identifier to use for the package in the generated source code.-aux_files
: A list of additional files that should be consulted toresolve e.g. embedded interfaces defined in a different file. This isspecified as a comma-separated list of elements of the formfoo=bar/baz.go
, wherebar/baz.go
is the source file andfoo
is thepackage name of that file used by the -source file.-build_flags
: (reflect mode only) Flags passed verbatim togo build
.-mock_names
: A list of custom names for generated mocks. This is specifiedas a comma-separated list of elements of the formRepository=MockSensorRepository,Endpoint=MockSensorEndpoint
, whereRepository
is the interface name andMockSensorRepository
is the desiredmock name (mock factory method and mock recorder will be named after the mock).If one of the interfaces has no custom name specified, then default namingconvention will be used.-self_package
: The full package import path for the generated code. Thepurpose of this flag is to prevent import cycles in the generated code bytrying to include its own package. This can happen if the mock's package isset to one of its inputs (usually the main one) and the output is stdio somockgen cannot detect the final output package. Setting this flag will thentell mockgen which import to exclude.-copyright_file
: Copyright file used to add copyright header to the resulting source code.-debug_parser
: Print out parser results only.-exec_only
: (reflect mode) If set, execute this reflection program.-prog_only
: (reflect mode) Only generate the reflection program; write it to stdout and exit.-write_package_comment
: Writes package documentation comment (godoc) if true. (default true)
For an example of the use ofmockgen
, see thesample/
directory. In simplecases, you will need only the-source
flag.
typeFoointerface {Bar(xint)int}funcSUT(fFoo) {// ...}
funcTestFoo(t*testing.T) {ctrl:=gomock.NewController(t)// Assert that Bar() is invoked.deferctrl.Finish()m:=NewMockFoo(ctrl)// Asserts that the first and only call to Bar() is passed 99.// Anything else will fail.m.EXPECT().Bar(gomock.Eq(99)).Return(101)SUT(m)}
If you are using a Go version of 1.14+, a mockgen version of 1.5.0+, and arepassing a *testing.T intogomock.NewController(t)
you no longer need to callctrl.Finish()
explicitly. It will be called for you automatically from a selfregisteredCleanup function.
typeFoointerface {Bar(xint)int}funcSUT(fFoo) {// ...}
funcTestFoo(t*testing.T) {ctrl:=gomock.NewController(t)deferctrl.Finish()m:=NewMockFoo(ctrl)// Does not make any assertions. Executes the anonymous functions and returns// its result when Bar is invoked with 99.m.EXPECT().Bar(gomock.Eq(99)).DoAndReturn(func(_int)int {time.Sleep(1*time.Second)return101 }).AnyTimes()// Does not make any assertions. Returns 103 when Bar is invoked with 101.m.EXPECT().Bar(gomock.Eq(101)).Return(103).AnyTimes()SUT(m)}
When a matcher reports a failure, it prints the received (Got
) vs theexpected (Want
) value.
Got: [3]Want: is equal to 2Expected call at user_test.go:33 doesn't match the argument at index 1.Got: [0 1 1 2 3]Want: is equal to 1
TheWant
value comes from the matcher'sString()
method. If the matcher'sdefault output doesn't meet your needs, then it can be modified as follows:
gomock.WantFormatter(gomock.StringerFunc(func()string {return"is equal to fifteen" }),gomock.Eq(15),)
This modifies thegomock.Eq(15)
matcher's output forWant:
fromis equal to 15
tois equal to fifteen
.
TheGot
value comes from the object'sString()
method if it is available.In some cases the output of an object is difficult to read (e.g.,[]byte
) andit would be helpful for the test to print it differently. The followingmodifies how theGot
value is formatted:
gomock.GotFormatterAdapter(gomock.GotFormatterFunc(func(iinterface{})string {// Leading 0sreturnfmt.Sprintf("%02d",i) }),gomock.Eq(15),)
If the received value is3
, then it will be printed as03
.