• Home
  • History
  • Annotate
Name Date Size #Lines LOC

..03-May-2022-

.github/H19-Feb-2021-

ci/H19-Feb-2021-

gomock/H19-Feb-2021-

mockgen/H19-Feb-2021-

sample/H19-Feb-2021-

.gitignoreH A D19-Feb-2021257

.goreleaser.ymlH A D19-Feb-2021756

AUTHORSH A D19-Feb-2021371

CONTRIBUTORSH A D19-Feb-20211.5 KiB

LICENSEH A D19-Feb-202111.1 KiB

README.mdH A D19-Feb-20216.9 KiB

go.modH A D19-Feb-2021132

go.sumH A D19-Feb-20211.7 KiB

README.md

1gomock [![Build Status][travis-ci-badge]][travis-ci] [![GoDoc][godoc-badge]][godoc]
2======
3
4GoMock is a mocking framework for the [Go programming language][golang]. It
5integrates well with Go's built-in `testing` package, but can be used in other
6contexts too.
7
8Installation
9------------
10
11Once you have [installed Go][golang-install], install the `mockgen` tool.
12
13To get the latest released version use:
14
15```bash
16GO111MODULE=on go get github.com/golang/mock/mockgen@v1.4.4
17```
18
19If you use `mockgen` in your CI pipeline, it may be more appropriate to fixate
20on a specific mockgen version.
21
22
23Documentation
24-------------
25
26After installing, you can use `go doc` to get documentation:
27
28```bash
29go doc github.com/golang/mock/gomock
30```
31
32Alternatively, there is an online reference for the package hosted on GoPkgDoc
33[here][gomock-ref].
34
35Running mockgen
36---------------
37
38`mockgen` has two modes of operation: source and reflect.
39
40#### Source mode
41Source mode generates mock interfaces from a source file.
42It is enabled by using the -source flag. Other flags that
43may be useful in this mode are -imports and -aux_files.
44
45Example:
46
47```bash
48mockgen -source=foo.go [other options]
49```
50
51#### Reflect mode
52Reflect mode generates mock interfaces by building a program
53that uses reflection to understand interfaces. It is enabled
54by passing two non-flag arguments: an import path, and a
55comma-separated list of symbols.
56
57You can use "." to refer to the current path's package.
58
59Example:
60
61```bash
62mockgen database/sql/driver Conn,Driver
63
64# Convenient for `go:generate`.
65mockgen . Conn,Driver
66```
67
68#### Flags
69The `mockgen` command is used to generate source code for a mock
70class given a Go source file containing interfaces to be mocked.
71It supports the following flags:
72
73* `-source`: A file containing interfaces to be mocked.
74
75* `-destination`: A file to which to write the resulting source code. If you
76    don't set this, the code is printed to standard output.
77
78* `-package`: The package to use for the resulting mock class
79    source code. If you don't set this, the package name is `mock_` concatenated
80    with the package of the input file.
81
82* `-imports`: A list of explicit imports that should be used in the resulting
83    source code, specified as a comma-separated list of elements of the form
84    `foo=bar/baz`, where `bar/baz` is the package being imported and `foo` is
85    the identifier to use for the package in the generated source code.
86
87* `-aux_files`: A list of additional files that should be consulted to
88    resolve e.g. embedded interfaces defined in a different file. This is
89    specified as a comma-separated list of elements of the form
90    `foo=bar/baz.go`, where `bar/baz.go` is the source file and `foo` is the
91    package name of that file used by the -source file.
92
93* `-build_flags`: (reflect mode only) Flags passed verbatim to `go build`.
94
95* `-mock_names`: A list of custom names for generated mocks. This is specified
96    as a comma-separated list of elements of the form
97    `Repository=MockSensorRepository,Endpoint=MockSensorEndpoint`, where
98    `Repository` is the interface name and `MockSensorRepository` is the desired
99    mock name (mock factory method and mock recorder will be named after the mock).
100    If one of the interfaces has no custom name specified, then default naming
101    convention will be used.
102
103* `-self_package`: The full package import path for the generated code. The purpose
104    of this flag is to prevent import cycles in the generated code by trying to include
105    its own package. This can happen if the mock's package is set to one of its
106    inputs (usually the main one) and the output is stdio so mockgen cannot detect the
107    final output package. Setting this flag will then tell mockgen which import to exclude.
108
109* `-copyright_file`: Copyright file used to add copyright header to the resulting source code.
110
111For an example of the use of `mockgen`, see the `sample/` directory. In simple
112cases, you will need only the `-source` flag.
113
114Building Mocks
115--------------
116
117```go
118type Foo interface {
119  Bar(x int) int
120}
121
122func SUT(f Foo) {
123 // ...
124}
125
126```
127
128```go
129func TestFoo(t *testing.T) {
130  ctrl := gomock.NewController(t)
131
132  // Assert that Bar() is invoked.
133  defer ctrl.Finish()
134
135  m := NewMockFoo(ctrl)
136
137  // Asserts that the first and only call to Bar() is passed 99.
138  // Anything else will fail.
139  m.
140    EXPECT().
141    Bar(gomock.Eq(99)).
142    Return(101)
143
144  SUT(m)
145}
146```
147
148If you are using a Go version of 1.14+, a mockgen version of 1.5.0+, and are
149passing a *testing.T into `gomock.NewController(t)` you no longer need to call
150`ctrl.Finish()` explicitly. It will be called for you automatically from a self
151registered [Cleanup](https://pkg.go.dev/testing?tab=doc#T.Cleanup) function.
152
153Building Stubs
154--------------
155
156```go
157type Foo interface {
158  Bar(x int) int
159}
160
161func SUT(f Foo) {
162 // ...
163}
164
165```
166
167```go
168func TestFoo(t *testing.T) {
169  ctrl := gomock.NewController(t)
170  defer ctrl.Finish()
171
172  m := NewMockFoo(ctrl)
173
174  // Does not make any assertions. Executes the anonymous functions and returns
175  // its result when Bar is invoked with 99.
176  m.
177    EXPECT().
178    Bar(gomock.Eq(99)).
179    DoAndReturn(func(_ int) int {
180      time.Sleep(1*time.Second)
181      return 101
182    }).
183    AnyTimes()
184
185  // Does not make any assertions. Returns 103 when Bar is invoked with 101.
186  m.
187    EXPECT().
188    Bar(gomock.Eq(101)).
189    Return(103).
190    AnyTimes()
191
192  SUT(m)
193}
194```
195
196### Modifying Failure Messages
197
198When a matcher reports a failure, it prints the received (`Got`) vs the
199expected (`Want`) value.
200
201```
202Got: [3]
203Want: is equal to 2
204Expected call at user_test.go:33 doesn't match the argument at index 1.
205Got: [0 1 1 2 3]
206Want: is equal to 1
207```
208
209##### Modifying `Want`
210
211The `Want` value comes from the matcher's `String()` method. If the matcher's
212default output doesn't meet your needs, then it can be modified as follows:
213
214```go
215gomock.WantFormatter(
216  gomock.StringerFunc(func() string { return "is equal to fifteen" }),
217  gomock.Eq(15),
218)
219```
220
221This modifies the `gomock.Eq(15)` matcher's output for `Want:` from `is equal
222to 15` to `is equal to fifteen`.
223
224##### Modifying `Got`
225
226The `Got` value comes from the object's `String()` method if it is available.
227In some cases the output of an object is difficult to read (e.g., `[]byte`) and
228it would be helpful for the test to print it differently. The following
229modifies how the `Got` value is formatted:
230
231```go
232gomock.GotFormatterAdapter(
233  gomock.GotFormatterFunc(func(i interface{}) string {
234    // Leading 0s
235    return fmt.Sprintf("%02d", i)
236  }),
237  gomock.Eq(15),
238)
239```
240
241If the received value is `3`, then it will be printed as `03`.
242
243[golang]:          http://golang.org/
244[golang-install]:  http://golang.org/doc/install.html#releases
245[gomock-ref]:      http://godoc.org/github.com/golang/mock/gomock
246[travis-ci-badge]: https://travis-ci.org/golang/mock.svg?branch=master
247[travis-ci]:       https://travis-ci.org/golang/mock
248[godoc-badge]:     https://godoc.org/github.com/golang/mock/gomock?status.svg
249[godoc]:           https://godoc.org/github.com/golang/mock/gomock
250