| 1 |
# gomock |
| 2 |
|
| 3 |
[![Build Status][ci-badge]][ci-runs] [![Go Reference][reference-badge]][reference] |
| 4 |
|
| 5 |
gomock is a mocking framework for the [Go programming language][golang]. It |
| 6 |
integrates well with Go's built-in `testing` package, but can be used in other |
| 7 |
contexts too. |
| 8 |
|
| 9 |
## Installation |
| 10 |
|
| 11 |
Once 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 |
|
| 16 |
To get the latest released version use: |
| 17 |
|
| 18 |
### Go version < 1.16 |
| 19 |
|
| 20 |
```bash |
| 21 |
GO111MODULE=on go get github.com/golang/mock/[email protected] |
| 22 |
``` |
| 23 |
|
| 24 |
### Go 1.16+ |
| 25 |
|
| 26 |
```bash |
| 27 |
go install github.com/golang/mock/[email protected] |
| 28 |
``` |
| 29 |
|
| 30 |
If you use `mockgen` in your CI pipeline, it may be more appropriate to fixate |
| 31 |
on a specific mockgen version. |
| 32 |
|
| 33 |
## Running mockgen |
| 34 |
|
| 35 |
`mockgen` has two modes of operation: source and reflect. |
| 36 |
|
| 37 |
### Source mode |
| 38 |
|
| 39 |
Source mode generates mock interfaces from a source file. |
| 40 |
It is enabled by using the -source flag. Other flags that |
| 41 |
may be useful in this mode are -imports and -aux_files. |
| 42 |
|
| 43 |
Example: |
| 44 |
|
| 45 |
```bash |
| 46 |
mockgen -source=foo.go [other options] |
| 47 |
``` |
| 48 |
|
| 49 |
### Reflect mode |
| 50 |
|
| 51 |
Reflect mode generates mock interfaces by building a program |
| 52 |
that uses reflection to understand interfaces. It is enabled |
| 53 |
by passing two non-flag arguments: an import path, and a |
| 54 |
comma-separated list of symbols. |
| 55 |
|
| 56 |
You can use "." to refer to the current path's package. |
| 57 |
|
| 58 |
Example: |
| 59 |
|
| 60 |
```bash |
| 61 |
mockgen database/sql/driver Conn,Driver |
| 62 |
|
| 63 |
# Convenient for `go:generate`. |
| 64 |
mockgen . Conn,Driver |
| 65 |
``` |
| 66 |
|
| 67 |
### Flags |
| 68 |
|
| 69 |
The `mockgen` command is used to generate source code for a mock |
| 70 |
class given a Go source file containing interfaces to be mocked. |
| 71 |
It 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 |
|
| 120 |
For an example of the use of `mockgen`, see the `sample/` directory. In simple |
| 121 |
cases, you will need only the `-source` flag. |
| 122 |
|
| 123 |
## Building Mocks |
| 124 |
|
| 125 |
```go |
| 126 |
type Foo interface { |
| 127 |
Bar(x int) int |
| 128 |
} |
| 129 |
|
| 130 |
func SUT(f Foo) { |
| 131 |
// ... |
| 132 |
} |
| 133 |
|
| 134 |
``` |
| 135 |
|
| 136 |
```go |
| 137 |
func 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 |
|
| 156 |
If you are using a Go version of 1.14+, a mockgen version of 1.5.0+, and are |
| 157 |
passing 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 |
| 159 |
registered [Cleanup](https://pkg.go.dev/testing?tab=doc#T.Cleanup) function. |
| 160 |
|
| 161 |
## Building Stubs |
| 162 |
|
| 163 |
```go |
| 164 |
type Foo interface { |
| 165 |
Bar(x int) int |
| 166 |
} |
| 167 |
|
| 168 |
func SUT(f Foo) { |
| 169 |
// ... |
| 170 |
} |
| 171 |
|
| 172 |
``` |
| 173 |
|
| 174 |
```go |
| 175 |
func 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 |
|
| 205 |
When a matcher reports a failure, it prints the received (`Got`) vs the |
| 206 |
expected (`Want`) value. |
| 207 |
|
| 208 |
```shell |
| 209 |
Got: [3] |
| 210 |
Want: is equal to 2 |
| 211 |
Expected call at user_test.go:33 doesn't match the argument at index 1. |
| 212 |
Got: [0 1 1 2 3] |
| 213 |
Want: is equal to 1 |
| 214 |
``` |
| 215 |
|
| 216 |
### Modifying `Want` |
| 217 |
|
| 218 |
The `Want` value comes from the matcher's `String()` method. If the matcher's |
| 219 |
default output doesn't meet your needs, then it can be modified as follows: |
| 220 |
|
| 221 |
```go |
| 222 |
gomock.WantFormatter( |
| 223 |
gomock.StringerFunc(func() string { return "is equal to fifteen" }), |
| 224 |
gomock.Eq(15), |
| 225 |
) |
| 226 |
``` |
| 227 |
|
| 228 |
This modifies the `gomock.Eq(15)` matcher's output for `Want:` from `is equal |
| 229 |
to 15` to `is equal to fifteen`. |
| 230 |
|
| 231 |
### Modifying `Got` |
| 232 |
|
| 233 |
The `Got` value comes from the object's `String()` method if it is available. |
| 234 |
In some cases the output of an object is difficult to read (e.g., `[]byte`) and |
| 235 |
it would be helpful for the test to print it differently. The following |
| 236 |
modifies how the `Got` value is formatted: |
| 237 |
|
| 238 |
```go |
| 239 |
gomock.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 |
|
| 248 |
If 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 |
| 263 |
cannot find package "." |
| 264 |
... github.com/golang/mock/mockgen/model |
| 265 |
``` |
| 266 |
|
| 267 |
If you come across this error while using reflect mode and vendoring |
| 268 |
dependencies there are three workarounds you can choose from: |
| 269 |
|
| 270 |
1. Use source mode. |
| 271 |
2. Include an empty import `import _ "github.com/golang/mock/mockgen/model"`. |
| 272 |
3. Add `--build_flags=--mod=mod` to your mockgen command. |
| 273 |
|
| 274 |
This error is due to changes in default behavior of the `go` command in more |
| 275 |
recent versions. More details can be found in |
| 276 |
[#494](https://github.com/golang/mock/issues/494). |