{"id":13413919,"url":"https://github.com/golang/mock","last_synced_at":"2025-10-05T18:31:08.844Z","repository":{"id":33681862,"uuid":"37334619","full_name":"golang/mock","owner":"golang","description":"GoMock is a mocking framework for the Go programming language.","archived":true,"fork":false,"pushed_at":"2024-01-08T08:00:38.000Z","size":669,"stargazers_count":9343,"open_issues_count":81,"forks_count":605,"subscribers_count":99,"default_branch":"main","last_synced_at":"2025-01-15T08:21:19.764Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/golang.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":".github/CODEOWNERS","security":null,"support":null,"governance":null,"roadmap":null,"authors":"AUTHORS","dei":null,"publiccode":null,"codemeta":null}},"created_at":"2015-06-12T17:15:11.000Z","updated_at":"2025-01-15T08:05:29.000Z","dependencies_parsed_at":"2024-06-18T10:45:02.891Z","dependency_job_id":"df0b1e57-79a5-40ea-9e91-c0a6beb23226","html_url":"https://github.com/golang/mock","commit_stats":{"total_commits":325,"total_committers":92,"mean_commits":3.532608695652174,"dds":0.7538461538461538,"last_synced_commit":"674a1c4a938e7b453416052327872571656801b7"},"previous_names":[],"tags_count":16,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/golang%2Fmock","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/golang%2Fmock/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/golang%2Fmock/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/golang%2Fmock/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/golang","download_url":"https://codeload.github.com/golang/mock/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":235432173,"owners_count":18989468,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-07-30T20:01:52.735Z","updated_at":"2025-10-05T18:31:08.440Z","avatar_url":"https://github.com/golang.png","language":"Go","readme":"# gomock\n\n**Update, June 2023**: _This repo and tool are no longer maintained.\nPlease see [go.uber.org/mock](https://github.com/uber/mock) for a maintained fork instead._\n\n[![Build Status][ci-badge]][ci-runs] [![Go Reference][reference-badge]][reference]\n\ngomock is a mocking framework for the [Go programming language][golang]. It\nintegrates well with Go's built-in `testing` package, but can be used in other\ncontexts too.\n\n## Installation\n\nOnce you have [installed Go][golang-install], install the `mockgen` tool.\n\n**Note**: If you have not done so already be sure to add `$GOPATH/bin` to your\n`PATH`.\n\nTo get the latest released version use:\n\n### Go version \u003c 1.16\n\n```bash\nGO111MODULE=on go get github.com/golang/mock/mockgen@v1.6.0\n```\n\n### Go 1.16+\n\n```bash\ngo install github.com/golang/mock/mockgen@v1.6.0\n```\n\nIf you use `mockgen` in your CI pipeline, it may be more appropriate to fixate\non a specific mockgen version. You should try to keep the library in sync with\nthe version of mockgen used to generate your mocks.\n\n## Running mockgen\n\n`mockgen` has two modes of operation: source and reflect.\n\n### Source mode\n\nSource mode generates mock interfaces from a source file.\nIt is enabled by using the -source flag. Other flags that\nmay be useful in this mode are -imports and -aux_files.\n\nExample:\n\n```bash\nmockgen -source=foo.go [other options]\n```\n\n### Reflect mode\n\nReflect mode generates mock interfaces by building a program\nthat uses reflection to understand interfaces. It is enabled\nby passing two non-flag arguments: an import path, and a\ncomma-separated list of symbols.\n\nYou can use \".\" to refer to the current path's package.\n\nExample:\n\n```bash\nmockgen database/sql/driver Conn,Driver\n\n# Convenient for `go:generate`.\nmockgen . Conn,Driver\n```\n\n### Flags\n\nThe `mockgen` command is used to generate source code for a mock\nclass given a Go source file containing interfaces to be mocked.\nIt supports the following flags:\n\n- `-source`: A file containing interfaces to be mocked.\n\n- `-destination`: A file to which to write the resulting source code. If you\n  don't set this, the code is printed to standard output.\n\n- `-package`: The package to use for the resulting mock class\n  source code. If you don't set this, the package name is `mock_` concatenated\n  with the package of the input file.\n\n- `-imports`: A list of explicit imports that should be used in the resulting\n  source code, specified as a comma-separated list of elements of the form\n  `foo=bar/baz`, where `bar/baz` is the package being imported and `foo` is\n  the identifier to use for the package in the generated source code.\n\n- `-aux_files`: A list of additional files that should be consulted to\n  resolve e.g. embedded interfaces defined in a different file. This is\n  specified as a comma-separated list of elements of the form\n  `foo=bar/baz.go`, where `bar/baz.go` is the source file and `foo` is the\n  package name of that file used by the -source file.\n\n- `-build_flags`: (reflect mode only) Flags passed verbatim to `go build`.\n\n- `-mock_names`: A list of custom names for generated mocks. This is specified\n  as a comma-separated list of elements of the form\n  `Repository=MockSensorRepository,Endpoint=MockSensorEndpoint`, where\n  `Repository` is the interface name and `MockSensorRepository` is the desired\n  mock name (mock factory method and mock recorder will be named after the mock).\n  If one of the interfaces has no custom name specified, then default naming\n  convention will be used.\n\n- `-self_package`: The full package import path for the generated code. The\n  purpose of this flag is to prevent import cycles in the generated code by\n  trying to include its own package. This can happen if the mock's package is\n  set to one of its inputs (usually the main one) and the output is stdio so\n  mockgen cannot detect the final output package. Setting this flag will then\n  tell mockgen which import to exclude.\n\n- `-copyright_file`: Copyright file used to add copyright header to the resulting source code.\n\n- `-debug_parser`: Print out parser results only.\n\n- `-exec_only`: (reflect mode) If set, execute this reflection program.\n\n- `-prog_only`: (reflect mode) Only generate the reflection program; write it to stdout and exit.\n\n- `-write_package_comment`: Writes package documentation comment (godoc) if true. (default true)\n\nFor an example of the use of `mockgen`, see the `sample/` directory. In simple\ncases, you will need only the `-source` flag.\n\n## Building Mocks\n\n```go\ntype Foo interface {\n  Bar(x int) int\n}\n\nfunc SUT(f Foo) {\n // ...\n}\n\n```\n\n```go\nfunc TestFoo(t *testing.T) {\n  ctrl := gomock.NewController(t)\n\n  // Assert that Bar() is invoked.\n  defer ctrl.Finish()\n\n  m := NewMockFoo(ctrl)\n\n  // Asserts that the first and only call to Bar() is passed 99.\n  // Anything else will fail.\n  m.\n    EXPECT().\n    Bar(gomock.Eq(99)).\n    Return(101)\n\n  SUT(m)\n}\n```\n\nIf you are using a Go version of 1.14+, a mockgen version of 1.5.0+, and are\npassing a *testing.T into `gomock.NewController(t)` you no longer need to call\n`ctrl.Finish()` explicitly. It will be called for you automatically from a self\nregistered [Cleanup](https://pkg.go.dev/testing?tab=doc#T.Cleanup) function.\n\n## Building Stubs\n\n```go\ntype Foo interface {\n  Bar(x int) int\n}\n\nfunc SUT(f Foo) {\n // ...\n}\n\n```\n\n```go\nfunc TestFoo(t *testing.T) {\n  ctrl := gomock.NewController(t)\n  defer ctrl.Finish()\n\n  m := NewMockFoo(ctrl)\n\n  // Does not make any assertions. Executes the anonymous functions and returns\n  // its result when Bar is invoked with 99.\n  m.\n    EXPECT().\n    Bar(gomock.Eq(99)).\n    DoAndReturn(func(_ int) int {\n      time.Sleep(1*time.Second)\n      return 101\n    }).\n    AnyTimes()\n\n  // Does not make any assertions. Returns 103 when Bar is invoked with 101.\n  m.\n    EXPECT().\n    Bar(gomock.Eq(101)).\n    Return(103).\n    AnyTimes()\n\n  SUT(m)\n}\n```\n\n## Modifying Failure Messages\n\nWhen a matcher reports a failure, it prints the received (`Got`) vs the\nexpected (`Want`) value.\n\n```shell\nGot: [3]\nWant: is equal to 2\nExpected call at user_test.go:33 doesn't match the argument at index 1.\nGot: [0 1 1 2 3]\nWant: is equal to 1\n```\n\n### Modifying `Want`\n\nThe `Want` value comes from the matcher's `String()` method. If the matcher's\ndefault output doesn't meet your needs, then it can be modified as follows:\n\n```go\ngomock.WantFormatter(\n  gomock.StringerFunc(func() string { return \"is equal to fifteen\" }),\n  gomock.Eq(15),\n)\n```\n\nThis modifies the `gomock.Eq(15)` matcher's output for `Want:` from `is equal\nto 15` to `is equal to fifteen`.\n\n### Modifying `Got`\n\nThe `Got` value comes from the object's `String()` method if it is available.\nIn some cases the output of an object is difficult to read (e.g., `[]byte`) and\nit would be helpful for the test to print it differently. The following\nmodifies how the `Got` value is formatted:\n\n```go\ngomock.GotFormatterAdapter(\n  gomock.GotFormatterFunc(func(i interface{}) string {\n    // Leading 0s\n    return fmt.Sprintf(\"%02d\", i)\n  }),\n  gomock.Eq(15),\n)\n```\n\nIf the received value is `3`, then it will be printed as `03`.\n\n[golang]:              http://golang.org/\n[golang-install]:      http://golang.org/doc/install.html#releases\n[gomock-reference]:    https://pkg.go.dev/github.com/golang/mock/gomock\n[ci-badge]:            https://github.com/golang/mock/actions/workflows/test.yaml/badge.svg\n[ci-runs]:             https://github.com/golang/mock/actions\n[reference-badge]:     https://pkg.go.dev/badge/github.com/golang/mock.svg\n[reference]:           https://pkg.go.dev/github.com/golang/mock\n\n## Debugging Errors\n\n### reflect vendoring error\n\n```text\ncannot find package \".\"\n... github.com/golang/mock/mockgen/model\n```\n\nIf you come across this error while using reflect mode and vendoring\ndependencies there are three workarounds you can choose from:\n\n1. Use source mode.\n2. Include an empty import `import _ \"github.com/golang/mock/mockgen/model\"`.\n3. Add `--build_flags=--mod=mod` to your mockgen command.\n\nThis error is due to changes in default behavior of the `go` command in more\nrecent versions. More details can be found in\n[#494](https://github.com/golang/mock/issues/494).\n","funding_links":[],"categories":["Go","开源类库","Links Úteis","Misc","Code Generation","Open source library","Testing","测试相关","测试","语言资源库","[](https://github.com/techschool/simplebank#setup-local-development)Setup local development","测试相关`测试库和测试数据集生成库`","Mock","\u003cspan id=\"测试-testing\"\u003e测试 Testing\u003c/span\u003e"],"sub_categories":["测试","Em Português","[⏫](#contents) Generate interface for a struct with [ifacemaker](https://github.com/vburenin/ifacemaker)","Test","Mock","HTTP Clients","Advanced Console UIs","查询语","交流","Mock 工具","go","HTTP客户端","[](https://github.com/techschool/simplebank#install-tools)Install tools","\u003cspan id=\"高级控制台用户界面-advanced-console-uis\"\u003e高级控制台用户界面 Advanced Console UIs\u003c/span\u003e"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgolang%2Fmock","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fgolang%2Fmock","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgolang%2Fmock/lists"}