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

..03-May-2022-

.github/H11-Jun-2021-

ci/H11-Jun-2021-

gomock/H11-Jun-2021-

mockgen/H11-Jun-2021-

sample/H11-Jun-2021-

.gitignoreH A D11-Jun-2021202

.goreleaser.ymlH A D11-Jun-2021770

AUTHORSH A D11-Jun-2021371

CONTRIBUTING.mdH A D11-Jun-2021627

CONTRIBUTORSH A D11-Jun-20211.5 KiB

LICENSEH A D11-Jun-202111.1 KiB

README.mdH A D11-Jun-20217.7 KiB

go.modH A D11-Jun-2021104

go.sumH A D11-Jun-20212.7 KiB

README.md

1# gomock
2
3[![Build Status][ci-badge]][ci-runs] [![Go Reference][reference-badge]][reference]
4
5gomock is a mocking framework for the [Go programming language][golang]. It
6integrates well with Go's built-in `testing` package, but can be used in other
7contexts too.
8
9## Installation
10
11Once you have [installed Go][golang-install], install the `mockgen` tool.
12
13**Note**: If you have not done so already be sure to add `$GOPATH/bin` to your
14`PATH`.
15
16To get the latest released version use:
17
18### Go version < 1.16
19
20```bash
21GO111MODULE=on go get github.com/golang/mock/mockgen@v1.5.0
22```
23
24### Go 1.16+
25
26```bash
27go install github.com/golang/mock/mockgen@v1.5.0
28```
29
30If you use `mockgen` in your CI pipeline, it may be more appropriate to fixate
31on a specific mockgen version.
32
33## Running mockgen
34
35`mockgen` has two modes of operation: source and reflect.
36
37### Source mode
38
39Source mode generates mock interfaces from a source file.
40It is enabled by using the -source flag. Other flags that
41may be useful in this mode are -imports and -aux_files.
42
43Example:
44
45```bash
46mockgen -source=foo.go [other options]
47```
48
49### Reflect mode
50
51Reflect mode generates mock interfaces by building a program
52that uses reflection to understand interfaces. It is enabled
53by passing two non-flag arguments: an import path, and a
54comma-separated list of symbols.
55
56You can use "." to refer to the current path's package.
57
58Example:
59
60```bash
61mockgen database/sql/driver Conn,Driver
62
63# Convenient for `go:generate`.
64mockgen . Conn,Driver
65```
66
67### Flags
68
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
104  purpose of this flag is to prevent import cycles in the generated code by
105  trying to include its own package. This can happen if the mock's package is
106  set to one of its inputs (usually the main one) and the output is stdio so
107  mockgen cannot detect the final output package. Setting this flag will then
108  tell mockgen which import to exclude.
109
110- `-copyright_file`: Copyright file used to add copyright header to the resulting source code.
111
112- `-debug_parser`: Print out parser results only.
113
114- `-exec_only`: (reflect mode) If set, execute this reflection program.
115
116- `-prog_only`: (reflect mode) Only generate the reflection program; write it to stdout and exit.
117
118- `-write_package_comment`: Writes package documentation comment (godoc) if true. (default true)
119
120For an example of the use of `mockgen`, see the `sample/` directory. In simple
121cases, you will need only the `-source` flag.
122
123## Building Mocks
124
125```go
126type Foo interface {
127  Bar(x int) int
128}
129
130func SUT(f Foo) {
131 // ...
132}
133
134```
135
136```go
137func TestFoo(t *testing.T) {
138  ctrl := gomock.NewController(t)
139
140  // Assert that Bar() is invoked.
141  defer ctrl.Finish()
142
143  m := NewMockFoo(ctrl)
144
145  // Asserts that the first and only call to Bar() is passed 99.
146  // Anything else will fail.
147  m.
148    EXPECT().
149    Bar(gomock.Eq(99)).
150    Return(101)
151
152  SUT(m)
153}
154```
155
156If you are using a Go version of 1.14+, a mockgen version of 1.5.0+, and are
157passing a *testing.T into `gomock.NewController(t)` you no longer need to call
158`ctrl.Finish()` explicitly. It will be called for you automatically from a self
159registered [Cleanup](https://pkg.go.dev/testing?tab=doc#T.Cleanup) function.
160
161## Building Stubs
162
163```go
164type Foo interface {
165  Bar(x int) int
166}
167
168func SUT(f Foo) {
169 // ...
170}
171
172```
173
174```go
175func TestFoo(t *testing.T) {
176  ctrl := gomock.NewController(t)
177  defer ctrl.Finish()
178
179  m := NewMockFoo(ctrl)
180
181  // Does not make any assertions. Executes the anonymous functions and returns
182  // its result when Bar is invoked with 99.
183  m.
184    EXPECT().
185    Bar(gomock.Eq(99)).
186    DoAndReturn(func(_ int) int {
187      time.Sleep(1*time.Second)
188      return 101
189    }).
190    AnyTimes()
191
192  // Does not make any assertions. Returns 103 when Bar is invoked with 101.
193  m.
194    EXPECT().
195    Bar(gomock.Eq(101)).
196    Return(103).
197    AnyTimes()
198
199  SUT(m)
200}
201```
202
203## Modifying Failure Messages
204
205When a matcher reports a failure, it prints the received (`Got`) vs the
206expected (`Want`) value.
207
208```shell
209Got: [3]
210Want: is equal to 2
211Expected call at user_test.go:33 doesn't match the argument at index 1.
212Got: [0 1 1 2 3]
213Want: is equal to 1
214```
215
216### Modifying `Want`
217
218The `Want` value comes from the matcher's `String()` method. If the matcher's
219default output doesn't meet your needs, then it can be modified as follows:
220
221```go
222gomock.WantFormatter(
223  gomock.StringerFunc(func() string { return "is equal to fifteen" }),
224  gomock.Eq(15),
225)
226```
227
228This modifies the `gomock.Eq(15)` matcher's output for `Want:` from `is equal
229to 15` to `is equal to fifteen`.
230
231### Modifying `Got`
232
233The `Got` value comes from the object's `String()` method if it is available.
234In some cases the output of an object is difficult to read (e.g., `[]byte`) and
235it would be helpful for the test to print it differently. The following
236modifies how the `Got` value is formatted:
237
238```go
239gomock.GotFormatterAdapter(
240  gomock.GotFormatterFunc(func(i interface{}) string {
241    // Leading 0s
242    return fmt.Sprintf("%02d", i)
243  }),
244  gomock.Eq(15),
245)
246```
247
248If the received value is `3`, then it will be printed as `03`.
249
250[golang]:              http://golang.org/
251[golang-install]:      http://golang.org/doc/install.html#releases
252[gomock-reference]:    https://pkg.go.dev/github.com/golang/mock/gomock
253[ci-badge]:            https://github.com/golang/mock/actions/workflows/test.yaml/badge.svg
254[ci-runs]:             https://github.com/golang/mock/actions
255[reference-badge]:     https://pkg.go.dev/badge/github.com/golang/mock.svg
256[reference]:           https://pkg.go.dev/github.com/golang/mock
257
258## Debugging Errors
259
260### reflect vendoring error
261
262```text
263cannot find package "."
264... github.com/golang/mock/mockgen/model
265```
266
267If you come across this error while using reflect mode and vendoring
268dependencies there are three workarounds you can choose from:
269
2701. Use source mode.
2712. Include an empty import `import _ "github.com/golang/mock/mockgen/model"`.
2723. Add `--build_flags=--mod=mod` to your mockgen command.
273
274This error is due to changes in default behavior of the `go` command in more
275recent versions. More details can be found in
276[#494](https://github.com/golang/mock/issues/494).
277