├── .github ├── CODEOWNERS ├── ISSUE_TEMPLATE │ ├── bug_report.md │ ├── config.yml │ └── feature_request.md └── workflows │ └── test.yaml ├── .gitignore ├── .goreleaser.yml ├── AUTHORS ├── CONTRIBUTING.md ├── CONTRIBUTORS ├── LICENSE ├── README.md ├── ci ├── check_panic_handling.sh └── test.sh ├── go.mod ├── go.sum ├── gomock ├── call.go ├── call_test.go ├── callset.go ├── callset_test.go ├── controller.go ├── controller_test.go ├── doc.go ├── example_test.go ├── internal │ └── mock_gomock │ │ └── mock_matcher.go ├── matchers.go ├── matchers_test.go └── mock_test.go ├── mockgen ├── generic_go118.go ├── generic_notgo118.go ├── internal │ └── tests │ │ ├── aux_imports_embedded_interface │ │ ├── README.md │ │ ├── bugreport.go │ │ ├── bugreport_mock.go │ │ ├── bugreport_test.go │ │ └── faux │ │ │ └── faux.go │ │ ├── const_array_length │ │ ├── input.go │ │ └── mock.go │ │ ├── copyright_file │ │ ├── input.go │ │ ├── mock.go │ │ └── mock_copyright_header │ │ ├── custom_package_name │ │ ├── README.md │ │ ├── client │ │ │ └── v1 │ │ │ │ └── client.go │ │ ├── greeter │ │ │ ├── greeter.go │ │ │ ├── greeter_mock_test.go │ │ │ └── greeter_test.go │ │ └── validator │ │ │ └── validate.go │ │ ├── dot_imports │ │ ├── input.go │ │ └── mock.go │ │ ├── empty_interface │ │ ├── input.go │ │ └── mock.go │ │ ├── extra_import │ │ ├── import.go │ │ └── mock.go │ │ ├── generated_identifier_conflict │ │ ├── README.md │ │ ├── bugreport.go │ │ ├── bugreport_mock.go │ │ └── bugreport_test.go │ │ ├── generics │ │ ├── external.go │ │ ├── generics.go │ │ ├── go.mod │ │ ├── go.sum │ │ ├── other │ │ │ └── other.go │ │ └── source │ │ │ ├── mock_external_test.go │ │ │ └── mock_generics_test.go │ │ ├── import_embedded_interface │ │ ├── bugreport.go │ │ ├── bugreport_mock.go │ │ ├── bugreport_test.go │ │ ├── ersatz │ │ │ └── ersatz.go │ │ ├── faux │ │ │ ├── conflict.go │ │ │ └── faux.go │ │ ├── foo.go │ │ ├── net.go │ │ ├── net_mock.go │ │ ├── net_test.go │ │ └── other │ │ │ ├── ersatz │ │ │ └── ersatz.go │ │ │ └── log │ │ │ └── log.go │ │ ├── import_source │ │ ├── README.md │ │ ├── definition │ │ │ ├── source.go │ │ │ └── source_mock.go │ │ └── source_mock.go │ │ ├── internal_pkg │ │ ├── generate.go │ │ └── subdir │ │ │ └── internal │ │ │ └── pkg │ │ │ ├── input.go │ │ │ ├── reflect_output │ │ │ └── mock.go │ │ │ └── source_output │ │ │ └── mock.go │ │ ├── missing_import │ │ ├── output │ │ │ └── source_mock.go │ │ └── source │ │ │ └── source.go │ │ ├── mock_in_test_package │ │ ├── README.md │ │ ├── mock_test.go │ │ └── user.go │ │ ├── overlapping_methods │ │ ├── interfaces.go │ │ ├── mock.go │ │ ├── overlap.go │ │ └── overlap_test.go │ │ ├── panicing_test │ │ ├── mock_test.go │ │ ├── panic.go │ │ └── panic_test.go │ │ ├── parenthesized_parameter_type │ │ ├── README.md │ │ ├── input.go │ │ └── mock.go │ │ ├── performance │ │ └── big_interface │ │ │ └── big_interface.go │ │ ├── self_package │ │ ├── mock.go │ │ └── types.go │ │ ├── test_package │ │ ├── foo.go │ │ ├── mock_test.go │ │ └── user_test.go │ │ ├── unexported_method │ │ ├── README.md │ │ ├── bugreport.go │ │ ├── bugreport_mock.go │ │ └── bugreport_test.go │ │ ├── vendor_dep │ │ ├── README.md │ │ ├── doc.go │ │ ├── mock.go │ │ ├── source_mock_package │ │ │ └── mock.go │ │ └── vendor_dep.go │ │ └── vendor_pkg │ │ ├── README.md │ │ ├── doc.go │ │ └── mock.go ├── mockgen.go ├── mockgen_test.go ├── model │ ├── model.go │ └── model_test.go ├── parse.go ├── parse_test.go ├── reflect.go └── version.go └── sample ├── README.md ├── concurrent ├── concurrent.go ├── concurrent_test.go └── mock │ └── concurrent_mock.go ├── imp1 └── imp1.go ├── imp2 └── imp2.go ├── imp3 └── imp3.go ├── imp4 └── imp4.go ├── mock_user_test.go ├── user.go └── user_test.go /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | * @codyoss 2 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Report a bug in gomock 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Actual behavior** A clear and concise description of what the bug is. 11 | 12 | **Expected behavior** A clear and concise description of what you expected to 13 | happen. 14 | 15 | **To Reproduce** Steps to reproduce the behavior 16 | 17 | 1. ... 18 | 2. ... 19 | 20 | **Additional Information** 21 | 22 | - gomock mode (reflect or source): 23 | - gomock version or git ref: 24 | - golang version: 25 | 26 | **Triage Notes for the Maintainers** 27 | 28 | 29 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/config.yml: -------------------------------------------------------------------------------- 1 | blank_issues_enabled: true 2 | #contact_links: 3 | # - name: GitHub Community Forum 4 | # url: https://github.community/ 5 | # about: Please ask and answer questions here. 6 | # - name: GitHub Security Bug Bounty 7 | # url: https://bounty.github.com/ 8 | # about: Please report security vulnerabilities here. 9 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Propose a new feature for gomock 4 | title: '' 5 | labels: 'type: feature request' 6 | assignees: '' 7 | 8 | --- 9 | 10 | *Requested feature* A clear description of the desired feature and an example of 11 | how it would be used. 12 | 13 | *Why the feature is needed* A clear description of how this feature is not 14 | served by existing functionality in gomock. 15 | 16 | *(Optional) Proposed solution* A clear description of a proposed method for 17 | adding this feature to gomock. 18 | -------------------------------------------------------------------------------- /.github/workflows/test.yaml: -------------------------------------------------------------------------------- 1 | name: Run tests 2 | on: 3 | push: 4 | branches: [main] 5 | pull_request: 6 | branches: [main] 7 | env: 8 | GO111MODULE: on 9 | jobs: 10 | test: 11 | strategy: 12 | matrix: 13 | go-version: [1.15.x, 1.18.x] 14 | os: [ubuntu-latest] 15 | runs-on: ${{ matrix.os }} 16 | steps: 17 | 18 | - name: Install Go 19 | uses: actions/setup-go@v2 20 | with: 21 | go-version: ${{ matrix.go-version }} 22 | 23 | - name: Checkout code 24 | uses: actions/checkout@v2 25 | 26 | - name: Vet and build 27 | run: | 28 | go vet ./... 29 | go build ./... 30 | 31 | - name: Install mockgen 32 | run: | 33 | go install github.com/golang/mock/mockgen 34 | 35 | - name: Run test script 36 | run: | 37 | ./ci/test.sh 38 | ./ci/check_panic_handling.sh 39 | 40 | - name: Run Go tests all 41 | if: ${{ startsWith(matrix.go-version, '1.18') }} 42 | run: | 43 | for i in $(find $PWD -name go.mod); do 44 | pushd $(dirname $i) 45 | go test ./... 46 | popd 47 | done 48 | 49 | - name: Run Go tests some 50 | if: ${{ startsWith(matrix.go-version, '1.18') == false }} 51 | run: | 52 | go test ./... 53 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Object files and binaries from go. 2 | *.[568] 3 | 4 | # Library files. 5 | *.a 6 | 7 | # Any file prefixed by an underscore. 8 | */_* 9 | 10 | # System 11 | .*.swp 12 | .DS_Store 13 | 14 | # The mockgen binary. 15 | mockgen/mockgen 16 | 17 | # Editors 18 | .vscode 19 | .idea 20 | 21 | # vendor directory used for IDEs 22 | /vendor 23 | -------------------------------------------------------------------------------- /.goreleaser.yml: -------------------------------------------------------------------------------- 1 | # Release automation via GoReleaser (goreleaser.com) 2 | # Requires a valid GITHUB_TOKEN envar prior to running `goreleaser` 3 | # See https://goreleaser.com/environment/ for more info 4 | --- 5 | release: 6 | github: 7 | owner: golang 8 | name: mock 9 | 10 | builds: 11 | - binary: mockgen 12 | goos: 13 | - darwin 14 | - windows 15 | - linux 16 | goarch: 17 | - amd64 18 | - arm64 19 | - 386 20 | env: 21 | - CGO_ENABLED=0 22 | - GO111MODULE=on 23 | - GOPROXY=https://proxy.golang.org 24 | - GOSUMDB=sum.golang.org 25 | main: ./mockgen/ 26 | 27 | archives: 28 | - format: tar.gz 29 | wrap_in_directory: true 30 | files: 31 | - LICENSE 32 | - README.md 33 | checksum: 34 | snapshot: 35 | name_template: "snap-{{ .Commit }}" 36 | changelog: 37 | sort: asc 38 | filters: 39 | exclude: 40 | - '^docs:' 41 | - '^test:' 42 | - 'README' 43 | -------------------------------------------------------------------------------- /AUTHORS: -------------------------------------------------------------------------------- 1 | # This is the official list of GoMock authors for copyright purposes. 2 | # This file is distinct from the CONTRIBUTORS files. 3 | # See the latter for an explanation. 4 | 5 | # Names should be added to this file as 6 | # Name or Organization 7 | # The email address is not required for organizations. 8 | 9 | # Please keep the list sorted. 10 | 11 | Alex Reece 12 | Google Inc. 13 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | First off, thank you for taking an interest to contribute to this project! 4 | 5 | ## Opening issues 6 | 7 | When opening a [new issue](https://github.com/golang/mock/issues/new/choose) 8 | please: 9 | 10 | 1. Make sure there are not other open/closed issues asking/reporting/requesting 11 | the same thing. 12 | 1. Choose one of our provided templates and fill out as much information as 13 | possible. 14 | 15 | ## Opening a Pull Requests 16 | 17 | We gladly accept contributions from the community. Before opening a pull request 18 | please make sure to create an issue for discussion first. This helps us decide 19 | what action should be taken in regards to the issue. 20 | -------------------------------------------------------------------------------- /CONTRIBUTORS: -------------------------------------------------------------------------------- 1 | # This is the official list of people who can contribute (and typically 2 | # have contributed) code to the gomock repository. 3 | # The AUTHORS file lists the copyright holders; this file 4 | # lists people. For example, Google employees are listed here 5 | # but not in AUTHORS, because Google holds the copyright. 6 | # 7 | # The submission process automatically checks to make sure 8 | # that people submitting code are listed in this file (by email address). 9 | # 10 | # Names should be added to this file only after verifying that 11 | # the individual or the individual's organization has agreed to 12 | # the appropriate Contributor License Agreement, found here: 13 | # 14 | # http://code.google.com/legal/individual-cla-v1.0.html 15 | # http://code.google.com/legal/corporate-cla-v1.0.html 16 | # 17 | # The agreement for individuals can be filled out on the web. 18 | # 19 | # When adding J Random Contributor's name to this file, 20 | # either J's name or J's organization's name should be 21 | # added to the AUTHORS file, depending on whether the 22 | # individual or corporate CLA was used. 23 | 24 | # Names should be added to this file like so: 25 | # Name 26 | # 27 | # An entry with two email addresses specifies that the 28 | # first address should be used in the submit logs and 29 | # that the second address should be recognized as the 30 | # same person when interacting with Rietveld. 31 | 32 | # Please keep the list sorted. 33 | 34 | Aaron Jacobs 35 | Alex Reece 36 | David Symonds 37 | Ryan Barrett 38 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # gomock 2 | 3 | **Update, June 2023**: _This repo and tool are no longer maintained. 4 | Please see [go.uber.org/mock](https://github.com/uber/mock) for a maintained fork instead._ 5 | 6 | [![Build Status][ci-badge]][ci-runs] [![Go Reference][reference-badge]][reference] 7 | 8 | gomock is a mocking framework for the [Go programming language][golang]. It 9 | integrates well with Go's built-in `testing` package, but can be used in other 10 | contexts too. 11 | 12 | ## Installation 13 | 14 | Once you have [installed Go][golang-install], install the `mockgen` tool. 15 | 16 | **Note**: If you have not done so already be sure to add `$GOPATH/bin` to your 17 | `PATH`. 18 | 19 | To get the latest released version use: 20 | 21 | ### Go version < 1.16 22 | 23 | ```bash 24 | GO111MODULE=on go get github.com/golang/mock/mockgen@v1.6.0 25 | ``` 26 | 27 | ### Go 1.16+ 28 | 29 | ```bash 30 | go install github.com/golang/mock/mockgen@v1.6.0 31 | ``` 32 | 33 | If you use `mockgen` in your CI pipeline, it may be more appropriate to fixate 34 | on a specific mockgen version. You should try to keep the library in sync with 35 | the version of mockgen used to generate your mocks. 36 | 37 | ## Running mockgen 38 | 39 | `mockgen` has two modes of operation: source and reflect. 40 | 41 | ### Source mode 42 | 43 | Source mode generates mock interfaces from a source file. 44 | It is enabled by using the -source flag. Other flags that 45 | may be useful in this mode are -imports and -aux_files. 46 | 47 | Example: 48 | 49 | ```bash 50 | mockgen -source=foo.go [other options] 51 | ``` 52 | 53 | ### Reflect mode 54 | 55 | Reflect mode generates mock interfaces by building a program 56 | that uses reflection to understand interfaces. It is enabled 57 | by passing two non-flag arguments: an import path, and a 58 | comma-separated list of symbols. 59 | 60 | You can use "." to refer to the current path's package. 61 | 62 | Example: 63 | 64 | ```bash 65 | mockgen database/sql/driver Conn,Driver 66 | 67 | # Convenient for `go:generate`. 68 | mockgen . Conn,Driver 69 | ``` 70 | 71 | ### Flags 72 | 73 | The `mockgen` command is used to generate source code for a mock 74 | class given a Go source file containing interfaces to be mocked. 75 | It supports the following flags: 76 | 77 | - `-source`: A file containing interfaces to be mocked. 78 | 79 | - `-destination`: A file to which to write the resulting source code. If you 80 | don't set this, the code is printed to standard output. 81 | 82 | - `-package`: The package to use for the resulting mock class 83 | source code. If you don't set this, the package name is `mock_` concatenated 84 | with the package of the input file. 85 | 86 | - `-imports`: A list of explicit imports that should be used in the resulting 87 | source code, specified as a comma-separated list of elements of the form 88 | `foo=bar/baz`, where `bar/baz` is the package being imported and `foo` is 89 | the identifier to use for the package in the generated source code. 90 | 91 | - `-aux_files`: A list of additional files that should be consulted to 92 | resolve e.g. embedded interfaces defined in a different file. This is 93 | specified as a comma-separated list of elements of the form 94 | `foo=bar/baz.go`, where `bar/baz.go` is the source file and `foo` is the 95 | package name of that file used by the -source file. 96 | 97 | - `-build_flags`: (reflect mode only) Flags passed verbatim to `go build`. 98 | 99 | - `-mock_names`: A list of custom names for generated mocks. This is specified 100 | as a comma-separated list of elements of the form 101 | `Repository=MockSensorRepository,Endpoint=MockSensorEndpoint`, where 102 | `Repository` is the interface name and `MockSensorRepository` is the desired 103 | mock name (mock factory method and mock recorder will be named after the mock). 104 | If one of the interfaces has no custom name specified, then default naming 105 | convention will be used. 106 | 107 | - `-self_package`: The full package import path for the generated code. The 108 | purpose of this flag is to prevent import cycles in the generated code by 109 | trying to include its own package. This can happen if the mock's package is 110 | set to one of its inputs (usually the main one) and the output is stdio so 111 | mockgen cannot detect the final output package. Setting this flag will then 112 | tell mockgen which import to exclude. 113 | 114 | - `-copyright_file`: Copyright file used to add copyright header to the resulting source code. 115 | 116 | - `-debug_parser`: Print out parser results only. 117 | 118 | - `-exec_only`: (reflect mode) If set, execute this reflection program. 119 | 120 | - `-prog_only`: (reflect mode) Only generate the reflection program; write it to stdout and exit. 121 | 122 | - `-write_package_comment`: Writes package documentation comment (godoc) if true. (default true) 123 | 124 | For an example of the use of `mockgen`, see the `sample/` directory. In simple 125 | cases, you will need only the `-source` flag. 126 | 127 | ## Building Mocks 128 | 129 | ```go 130 | type Foo interface { 131 | Bar(x int) int 132 | } 133 | 134 | func SUT(f Foo) { 135 | // ... 136 | } 137 | 138 | ``` 139 | 140 | ```go 141 | func TestFoo(t *testing.T) { 142 | ctrl := gomock.NewController(t) 143 | 144 | // Assert that Bar() is invoked. 145 | defer ctrl.Finish() 146 | 147 | m := NewMockFoo(ctrl) 148 | 149 | // Asserts that the first and only call to Bar() is passed 99. 150 | // Anything else will fail. 151 | m. 152 | EXPECT(). 153 | Bar(gomock.Eq(99)). 154 | Return(101) 155 | 156 | SUT(m) 157 | } 158 | ``` 159 | 160 | If you are using a Go version of 1.14+, a mockgen version of 1.5.0+, and are 161 | passing a *testing.T into `gomock.NewController(t)` you no longer need to call 162 | `ctrl.Finish()` explicitly. It will be called for you automatically from a self 163 | registered [Cleanup](https://pkg.go.dev/testing?tab=doc#T.Cleanup) function. 164 | 165 | ## Building Stubs 166 | 167 | ```go 168 | type Foo interface { 169 | Bar(x int) int 170 | } 171 | 172 | func SUT(f Foo) { 173 | // ... 174 | } 175 | 176 | ``` 177 | 178 | ```go 179 | func TestFoo(t *testing.T) { 180 | ctrl := gomock.NewController(t) 181 | defer ctrl.Finish() 182 | 183 | m := NewMockFoo(ctrl) 184 | 185 | // Does not make any assertions. Executes the anonymous functions and returns 186 | // its result when Bar is invoked with 99. 187 | m. 188 | EXPECT(). 189 | Bar(gomock.Eq(99)). 190 | DoAndReturn(func(_ int) int { 191 | time.Sleep(1*time.Second) 192 | return 101 193 | }). 194 | AnyTimes() 195 | 196 | // Does not make any assertions. Returns 103 when Bar is invoked with 101. 197 | m. 198 | EXPECT(). 199 | Bar(gomock.Eq(101)). 200 | Return(103). 201 | AnyTimes() 202 | 203 | SUT(m) 204 | } 205 | ``` 206 | 207 | ## Modifying Failure Messages 208 | 209 | When a matcher reports a failure, it prints the received (`Got`) vs the 210 | expected (`Want`) value. 211 | 212 | ```shell 213 | Got: [3] 214 | Want: is equal to 2 215 | Expected call at user_test.go:33 doesn't match the argument at index 1. 216 | Got: [0 1 1 2 3] 217 | Want: is equal to 1 218 | ``` 219 | 220 | ### Modifying `Want` 221 | 222 | The `Want` value comes from the matcher's `String()` method. If the matcher's 223 | default output doesn't meet your needs, then it can be modified as follows: 224 | 225 | ```go 226 | gomock.WantFormatter( 227 | gomock.StringerFunc(func() string { return "is equal to fifteen" }), 228 | gomock.Eq(15), 229 | ) 230 | ``` 231 | 232 | This modifies the `gomock.Eq(15)` matcher's output for `Want:` from `is equal 233 | to 15` to `is equal to fifteen`. 234 | 235 | ### Modifying `Got` 236 | 237 | The `Got` value comes from the object's `String()` method if it is available. 238 | In some cases the output of an object is difficult to read (e.g., `[]byte`) and 239 | it would be helpful for the test to print it differently. The following 240 | modifies how the `Got` value is formatted: 241 | 242 | ```go 243 | gomock.GotFormatterAdapter( 244 | gomock.GotFormatterFunc(func(i interface{}) string { 245 | // Leading 0s 246 | return fmt.Sprintf("%02d", i) 247 | }), 248 | gomock.Eq(15), 249 | ) 250 | ``` 251 | 252 | If the received value is `3`, then it will be printed as `03`. 253 | 254 | [golang]: http://golang.org/ 255 | [golang-install]: http://golang.org/doc/install.html#releases 256 | [gomock-reference]: https://pkg.go.dev/github.com/golang/mock/gomock 257 | [ci-badge]: https://github.com/golang/mock/actions/workflows/test.yaml/badge.svg 258 | [ci-runs]: https://github.com/golang/mock/actions 259 | [reference-badge]: https://pkg.go.dev/badge/github.com/golang/mock.svg 260 | [reference]: https://pkg.go.dev/github.com/golang/mock 261 | 262 | ## Debugging Errors 263 | 264 | ### reflect vendoring error 265 | 266 | ```text 267 | cannot find package "." 268 | ... github.com/golang/mock/mockgen/model 269 | ``` 270 | 271 | If you come across this error while using reflect mode and vendoring 272 | dependencies there are three workarounds you can choose from: 273 | 274 | 1. Use source mode. 275 | 2. Include an empty import `import _ "github.com/golang/mock/mockgen/model"`. 276 | 3. Add `--build_flags=--mod=mod` to your mockgen command. 277 | 278 | This error is due to changes in default behavior of the `go` command in more 279 | recent versions. More details can be found in 280 | [#494](https://github.com/golang/mock/issues/494). 281 | -------------------------------------------------------------------------------- /ci/check_panic_handling.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Copyright 2010 Google LLC. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | # This script is used to ensure that panics are properly reported in tests. 17 | 18 | set -eux 19 | 20 | pushd mockgen/internal/tests/panicing_test 21 | go test -v -tags=panictest -run TestDanger_Panics_Explicit | grep "Danger, Will Robinson!" 22 | go test -v -tags=panictest -run TestDanger_Panics_Implicit | grep "Danger, Will Robinson!" 23 | popd 24 | -------------------------------------------------------------------------------- /ci/test.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # This script is used to ensure that the go.mod file is up to date. 3 | 4 | set -euo pipefail 5 | 6 | if [[ $(go version) != *"go1.18"* ]]; then 7 | exit 0 8 | fi 9 | 10 | for i in $(find $PWD -name go.mod); do 11 | pushd $(dirname $i) 12 | go mod tidy 13 | popd 14 | done 15 | 16 | if [ ! -z "$(git status --porcelain)" ]; then 17 | git status 18 | git diff 19 | echo 20 | echo "The go.mod is not up to date." 21 | exit 1 22 | fi 23 | 24 | BASE_DIR="$PWD" 25 | TEMP_DIR=$(mktemp -d) 26 | function cleanup() { 27 | rm -rf "${TEMP_DIR}" 28 | } 29 | trap cleanup EXIT 30 | 31 | cp -r . "${TEMP_DIR}/" 32 | cd $TEMP_DIR 33 | 34 | for i in $(find $PWD -name go.mod); do 35 | pushd $(dirname $i) 36 | go generate ./... 37 | popd 38 | done 39 | 40 | if ! diff -r . "${BASE_DIR}"; then 41 | echo 42 | echo "The generated files aren't up to date." 43 | echo "Update them with the 'go generate ./...' command." 44 | exit 1 45 | fi 46 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/golang/mock 2 | 3 | require ( 4 | golang.org/x/mod v0.5.1 5 | golang.org/x/tools v0.1.8 6 | ) 7 | 8 | go 1.15 9 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/yuin/goldmark v1.4.1 h1:/vn0k+RBvwlxEmP5E7SZMqNxPhfMVFEJiykr15/0XKM= 2 | github.com/yuin/goldmark v1.4.1/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= 3 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 4 | golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= 5 | golang.org/x/mod v0.5.1 h1:OJxoQ/rynoF0dcCdI7cLPktw/hR2cueqYfjm43oqK38= 6 | golang.org/x/mod v0.5.1/go.mod h1:5OXOZSfqPIIbmVBIIKWRFfZjPR0E5r58TLhUjH0a2Ro= 7 | golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= 8 | golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= 9 | golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= 10 | golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 11 | golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 12 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 13 | golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 14 | golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 15 | golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 16 | golang.org/x/sys v0.0.0-20211019181941-9d821ace8654 h1:id054HUawV2/6IGm2IV8KZQjqtwAOo2CYlOToYqa0d0= 17 | golang.org/x/sys v0.0.0-20211019181941-9d821ace8654/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 18 | golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= 19 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 20 | golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= 21 | golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= 22 | golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 23 | golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= 24 | golang.org/x/tools v0.1.8 h1:P1HhGGuLW4aAclzjtmJdf0mJOjVUZUzOTqkAkWL+l6w= 25 | golang.org/x/tools v0.1.8/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU= 26 | golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 27 | golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 28 | golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= 29 | golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 30 | -------------------------------------------------------------------------------- /gomock/callset.go: -------------------------------------------------------------------------------- 1 | // Copyright 2011 Google Inc. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package gomock 16 | 17 | import ( 18 | "bytes" 19 | "errors" 20 | "fmt" 21 | ) 22 | 23 | // callSet represents a set of expected calls, indexed by receiver and method 24 | // name. 25 | type callSet struct { 26 | // Calls that are still expected. 27 | expected map[callSetKey][]*Call 28 | // Calls that have been exhausted. 29 | exhausted map[callSetKey][]*Call 30 | } 31 | 32 | // callSetKey is the key in the maps in callSet 33 | type callSetKey struct { 34 | receiver interface{} 35 | fname string 36 | } 37 | 38 | func newCallSet() *callSet { 39 | return &callSet{make(map[callSetKey][]*Call), make(map[callSetKey][]*Call)} 40 | } 41 | 42 | // Add adds a new expected call. 43 | func (cs callSet) Add(call *Call) { 44 | key := callSetKey{call.receiver, call.method} 45 | m := cs.expected 46 | if call.exhausted() { 47 | m = cs.exhausted 48 | } 49 | m[key] = append(m[key], call) 50 | } 51 | 52 | // Remove removes an expected call. 53 | func (cs callSet) Remove(call *Call) { 54 | key := callSetKey{call.receiver, call.method} 55 | calls := cs.expected[key] 56 | for i, c := range calls { 57 | if c == call { 58 | // maintain order for remaining calls 59 | cs.expected[key] = append(calls[:i], calls[i+1:]...) 60 | cs.exhausted[key] = append(cs.exhausted[key], call) 61 | break 62 | } 63 | } 64 | } 65 | 66 | // FindMatch searches for a matching call. Returns error with explanation message if no call matched. 67 | func (cs callSet) FindMatch(receiver interface{}, method string, args []interface{}) (*Call, error) { 68 | key := callSetKey{receiver, method} 69 | 70 | // Search through the expected calls. 71 | expected := cs.expected[key] 72 | var callsErrors bytes.Buffer 73 | for _, call := range expected { 74 | err := call.matches(args) 75 | if err != nil { 76 | _, _ = fmt.Fprintf(&callsErrors, "\n%v", err) 77 | } else { 78 | return call, nil 79 | } 80 | } 81 | 82 | // If we haven't found a match then search through the exhausted calls so we 83 | // get useful error messages. 84 | exhausted := cs.exhausted[key] 85 | for _, call := range exhausted { 86 | if err := call.matches(args); err != nil { 87 | _, _ = fmt.Fprintf(&callsErrors, "\n%v", err) 88 | continue 89 | } 90 | _, _ = fmt.Fprintf( 91 | &callsErrors, "all expected calls for method %q have been exhausted", method, 92 | ) 93 | } 94 | 95 | if len(expected)+len(exhausted) == 0 { 96 | _, _ = fmt.Fprintf(&callsErrors, "there are no expected calls of the method %q for that receiver", method) 97 | } 98 | 99 | return nil, errors.New(callsErrors.String()) 100 | } 101 | 102 | // Failures returns the calls that are not satisfied. 103 | func (cs callSet) Failures() []*Call { 104 | failures := make([]*Call, 0, len(cs.expected)) 105 | for _, calls := range cs.expected { 106 | for _, call := range calls { 107 | if !call.satisfied() { 108 | failures = append(failures, call) 109 | } 110 | } 111 | } 112 | return failures 113 | } 114 | -------------------------------------------------------------------------------- /gomock/callset_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2011 Google Inc. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package gomock 16 | 17 | import ( 18 | "reflect" 19 | "testing" 20 | ) 21 | 22 | type receiverType struct{} 23 | 24 | func (receiverType) Func() {} 25 | 26 | func TestCallSetAdd(t *testing.T) { 27 | method := "TestMethod" 28 | var receiver interface{} = "TestReceiver" 29 | cs := newCallSet() 30 | 31 | numCalls := 10 32 | for i := 0; i < numCalls; i++ { 33 | cs.Add(newCall(t, receiver, method, reflect.TypeOf(receiverType{}.Func))) 34 | } 35 | 36 | call, err := cs.FindMatch(receiver, method, []interface{}{}) 37 | if err != nil { 38 | t.Fatalf("FindMatch: %v", err) 39 | } 40 | if call == nil { 41 | t.Fatalf("FindMatch: Got nil, want non-nil *Call") 42 | } 43 | } 44 | 45 | func TestCallSetRemove(t *testing.T) { 46 | method := "TestMethod" 47 | var receiver interface{} = "TestReceiver" 48 | 49 | cs := newCallSet() 50 | ourCalls := []*Call{} 51 | 52 | numCalls := 10 53 | for i := 0; i < numCalls; i++ { 54 | // NOTE: abuse the `numCalls` value to convey initial ordering of mocked calls 55 | generatedCall := &Call{receiver: receiver, method: method, numCalls: i} 56 | cs.Add(generatedCall) 57 | ourCalls = append(ourCalls, generatedCall) 58 | } 59 | 60 | // validateOrder validates that the calls in the array are ordered as they were added 61 | validateOrder := func(calls []*Call) { 62 | // lastNum tracks the last `numCalls` (call order) value seen 63 | lastNum := -1 64 | for _, c := range calls { 65 | if lastNum >= c.numCalls { 66 | t.Errorf("found call %d after call %d", c.numCalls, lastNum) 67 | } 68 | lastNum = c.numCalls 69 | } 70 | } 71 | 72 | for _, c := range ourCalls { 73 | validateOrder(cs.expected[callSetKey{receiver, method}]) 74 | cs.Remove(c) 75 | } 76 | } 77 | 78 | func TestCallSetFindMatch(t *testing.T) { 79 | t.Run("call is exhausted", func(t *testing.T) { 80 | cs := callSet{} 81 | var receiver interface{} = "TestReceiver" 82 | method := "TestMethod" 83 | args := []interface{}{} 84 | 85 | c1 := newCall(t, receiver, method, reflect.TypeOf(receiverType{}.Func)) 86 | cs.exhausted = map[callSetKey][]*Call{ 87 | {receiver: receiver, fname: method}: {c1}, 88 | } 89 | 90 | _, err := cs.FindMatch(receiver, method, args) 91 | if err == nil { 92 | t.Fatal("expected error, but was nil") 93 | } 94 | 95 | if err.Error() == "" { 96 | t.Fatal("expected error to have message, but was empty") 97 | } 98 | }) 99 | } 100 | -------------------------------------------------------------------------------- /gomock/controller.go: -------------------------------------------------------------------------------- 1 | // Copyright 2010 Google Inc. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package gomock 16 | 17 | import ( 18 | "context" 19 | "fmt" 20 | "reflect" 21 | "runtime" 22 | "sync" 23 | ) 24 | 25 | // A TestReporter is something that can be used to report test failures. It 26 | // is satisfied by the standard library's *testing.T. 27 | type TestReporter interface { 28 | Errorf(format string, args ...interface{}) 29 | Fatalf(format string, args ...interface{}) 30 | } 31 | 32 | // TestHelper is a TestReporter that has the Helper method. It is satisfied 33 | // by the standard library's *testing.T. 34 | type TestHelper interface { 35 | TestReporter 36 | Helper() 37 | } 38 | 39 | // cleanuper is used to check if TestHelper also has the `Cleanup` method. A 40 | // common pattern is to pass in a `*testing.T` to 41 | // `NewController(t TestReporter)`. In Go 1.14+, `*testing.T` has a cleanup 42 | // method. This can be utilized to call `Finish()` so the caller of this library 43 | // does not have to. 44 | type cleanuper interface { 45 | Cleanup(func()) 46 | } 47 | 48 | // A Controller represents the top-level control of a mock ecosystem. It 49 | // defines the scope and lifetime of mock objects, as well as their 50 | // expectations. It is safe to call Controller's methods from multiple 51 | // goroutines. Each test should create a new Controller and invoke Finish via 52 | // defer. 53 | // 54 | // func TestFoo(t *testing.T) { 55 | // ctrl := gomock.NewController(t) 56 | // defer ctrl.Finish() 57 | // // .. 58 | // } 59 | // 60 | // func TestBar(t *testing.T) { 61 | // t.Run("Sub-Test-1", st) { 62 | // ctrl := gomock.NewController(st) 63 | // defer ctrl.Finish() 64 | // // .. 65 | // }) 66 | // t.Run("Sub-Test-2", st) { 67 | // ctrl := gomock.NewController(st) 68 | // defer ctrl.Finish() 69 | // // .. 70 | // }) 71 | // }) 72 | type Controller struct { 73 | // T should only be called within a generated mock. It is not intended to 74 | // be used in user code and may be changed in future versions. T is the 75 | // TestReporter passed in when creating the Controller via NewController. 76 | // If the TestReporter does not implement a TestHelper it will be wrapped 77 | // with a nopTestHelper. 78 | T TestHelper 79 | mu sync.Mutex 80 | expectedCalls *callSet 81 | finished bool 82 | } 83 | 84 | // NewController returns a new Controller. It is the preferred way to create a 85 | // Controller. 86 | // 87 | // New in go1.14+, if you are passing a *testing.T into this function you no 88 | // longer need to call ctrl.Finish() in your test methods. 89 | func NewController(t TestReporter) *Controller { 90 | h, ok := t.(TestHelper) 91 | if !ok { 92 | h = &nopTestHelper{t} 93 | } 94 | ctrl := &Controller{ 95 | T: h, 96 | expectedCalls: newCallSet(), 97 | } 98 | if c, ok := isCleanuper(ctrl.T); ok { 99 | c.Cleanup(func() { 100 | ctrl.T.Helper() 101 | ctrl.finish(true, nil) 102 | }) 103 | } 104 | 105 | return ctrl 106 | } 107 | 108 | type cancelReporter struct { 109 | t TestHelper 110 | cancel func() 111 | } 112 | 113 | func (r *cancelReporter) Errorf(format string, args ...interface{}) { 114 | r.t.Errorf(format, args...) 115 | } 116 | func (r *cancelReporter) Fatalf(format string, args ...interface{}) { 117 | defer r.cancel() 118 | r.t.Fatalf(format, args...) 119 | } 120 | 121 | func (r *cancelReporter) Helper() { 122 | r.t.Helper() 123 | } 124 | 125 | // WithContext returns a new Controller and a Context, which is cancelled on any 126 | // fatal failure. 127 | func WithContext(ctx context.Context, t TestReporter) (*Controller, context.Context) { 128 | h, ok := t.(TestHelper) 129 | if !ok { 130 | h = &nopTestHelper{t: t} 131 | } 132 | 133 | ctx, cancel := context.WithCancel(ctx) 134 | return NewController(&cancelReporter{t: h, cancel: cancel}), ctx 135 | } 136 | 137 | type nopTestHelper struct { 138 | t TestReporter 139 | } 140 | 141 | func (h *nopTestHelper) Errorf(format string, args ...interface{}) { 142 | h.t.Errorf(format, args...) 143 | } 144 | func (h *nopTestHelper) Fatalf(format string, args ...interface{}) { 145 | h.t.Fatalf(format, args...) 146 | } 147 | 148 | func (h nopTestHelper) Helper() {} 149 | 150 | // RecordCall is called by a mock. It should not be called by user code. 151 | func (ctrl *Controller) RecordCall(receiver interface{}, method string, args ...interface{}) *Call { 152 | ctrl.T.Helper() 153 | 154 | recv := reflect.ValueOf(receiver) 155 | for i := 0; i < recv.Type().NumMethod(); i++ { 156 | if recv.Type().Method(i).Name == method { 157 | return ctrl.RecordCallWithMethodType(receiver, method, recv.Method(i).Type(), args...) 158 | } 159 | } 160 | ctrl.T.Fatalf("gomock: failed finding method %s on %T", method, receiver) 161 | panic("unreachable") 162 | } 163 | 164 | // RecordCallWithMethodType is called by a mock. It should not be called by user code. 165 | func (ctrl *Controller) RecordCallWithMethodType(receiver interface{}, method string, methodType reflect.Type, args ...interface{}) *Call { 166 | ctrl.T.Helper() 167 | 168 | call := newCall(ctrl.T, receiver, method, methodType, args...) 169 | 170 | ctrl.mu.Lock() 171 | defer ctrl.mu.Unlock() 172 | ctrl.expectedCalls.Add(call) 173 | 174 | return call 175 | } 176 | 177 | // Call is called by a mock. It should not be called by user code. 178 | func (ctrl *Controller) Call(receiver interface{}, method string, args ...interface{}) []interface{} { 179 | ctrl.T.Helper() 180 | 181 | // Nest this code so we can use defer to make sure the lock is released. 182 | actions := func() []func([]interface{}) []interface{} { 183 | ctrl.T.Helper() 184 | ctrl.mu.Lock() 185 | defer ctrl.mu.Unlock() 186 | 187 | expected, err := ctrl.expectedCalls.FindMatch(receiver, method, args) 188 | if err != nil { 189 | // callerInfo's skip should be updated if the number of calls between the user's test 190 | // and this line changes, i.e. this code is wrapped in another anonymous function. 191 | // 0 is us, 1 is controller.Call(), 2 is the generated mock, and 3 is the user's test. 192 | origin := callerInfo(3) 193 | ctrl.T.Fatalf("Unexpected call to %T.%v(%v) at %s because: %s", receiver, method, args, origin, err) 194 | } 195 | 196 | // Two things happen here: 197 | // * the matching call no longer needs to check prerequite calls, 198 | // * and the prerequite calls are no longer expected, so remove them. 199 | preReqCalls := expected.dropPrereqs() 200 | for _, preReqCall := range preReqCalls { 201 | ctrl.expectedCalls.Remove(preReqCall) 202 | } 203 | 204 | actions := expected.call() 205 | if expected.exhausted() { 206 | ctrl.expectedCalls.Remove(expected) 207 | } 208 | return actions 209 | }() 210 | 211 | var rets []interface{} 212 | for _, action := range actions { 213 | if r := action(args); r != nil { 214 | rets = r 215 | } 216 | } 217 | 218 | return rets 219 | } 220 | 221 | // Finish checks to see if all the methods that were expected to be called 222 | // were called. It should be invoked for each Controller. It is not idempotent 223 | // and therefore can only be invoked once. 224 | // 225 | // New in go1.14+, if you are passing a *testing.T into NewController function you no 226 | // longer need to call ctrl.Finish() in your test methods. 227 | func (ctrl *Controller) Finish() { 228 | // If we're currently panicking, probably because this is a deferred call. 229 | // This must be recovered in the deferred function. 230 | err := recover() 231 | ctrl.finish(false, err) 232 | } 233 | 234 | func (ctrl *Controller) finish(cleanup bool, panicErr interface{}) { 235 | ctrl.T.Helper() 236 | 237 | ctrl.mu.Lock() 238 | defer ctrl.mu.Unlock() 239 | 240 | if ctrl.finished { 241 | if _, ok := isCleanuper(ctrl.T); !ok { 242 | ctrl.T.Fatalf("Controller.Finish was called more than once. It has to be called exactly once.") 243 | } 244 | return 245 | } 246 | ctrl.finished = true 247 | 248 | // Short-circuit, pass through the panic. 249 | if panicErr != nil { 250 | panic(panicErr) 251 | } 252 | 253 | // Check that all remaining expected calls are satisfied. 254 | failures := ctrl.expectedCalls.Failures() 255 | for _, call := range failures { 256 | ctrl.T.Errorf("missing call(s) to %v", call) 257 | } 258 | if len(failures) != 0 { 259 | if !cleanup { 260 | ctrl.T.Fatalf("aborting test due to missing call(s)") 261 | return 262 | } 263 | ctrl.T.Errorf("aborting test due to missing call(s)") 264 | } 265 | } 266 | 267 | // callerInfo returns the file:line of the call site. skip is the number 268 | // of stack frames to skip when reporting. 0 is callerInfo's call site. 269 | func callerInfo(skip int) string { 270 | if _, file, line, ok := runtime.Caller(skip + 1); ok { 271 | return fmt.Sprintf("%s:%d", file, line) 272 | } 273 | return "unknown file" 274 | } 275 | 276 | // isCleanuper checks it if t's base TestReporter has a Cleanup method. 277 | func isCleanuper(t TestReporter) (cleanuper, bool) { 278 | tr := unwrapTestReporter(t) 279 | c, ok := tr.(cleanuper) 280 | return c, ok 281 | } 282 | 283 | // unwrapTestReporter unwraps TestReporter to the base implementation. 284 | func unwrapTestReporter(t TestReporter) TestReporter { 285 | tr := t 286 | switch nt := t.(type) { 287 | case *cancelReporter: 288 | tr = nt.t 289 | if h, check := tr.(*nopTestHelper); check { 290 | tr = h.t 291 | } 292 | case *nopTestHelper: 293 | tr = nt.t 294 | default: 295 | // not wrapped 296 | } 297 | return tr 298 | } 299 | -------------------------------------------------------------------------------- /gomock/doc.go: -------------------------------------------------------------------------------- 1 | // Copyright 2022 Google LLC 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | // Package gomock is a mock framework for Go. 16 | // 17 | // Standard usage: 18 | // (1) Define an interface that you wish to mock. 19 | // type MyInterface interface { 20 | // SomeMethod(x int64, y string) 21 | // } 22 | // (2) Use mockgen to generate a mock from the interface. 23 | // (3) Use the mock in a test: 24 | // func TestMyThing(t *testing.T) { 25 | // mockCtrl := gomock.NewController(t)// 26 | // mockObj := something.NewMockMyInterface(mockCtrl) 27 | // mockObj.EXPECT().SomeMethod(4, "blah") 28 | // // pass mockObj to a real object and play with it. 29 | // } 30 | // 31 | // By default, expected calls are not enforced to run in any particular order. 32 | // Call order dependency can be enforced by use of InOrder and/or Call.After. 33 | // Call.After can create more varied call order dependencies, but InOrder is 34 | // often more convenient. 35 | // 36 | // The following examples create equivalent call order dependencies. 37 | // 38 | // Example of using Call.After to chain expected call order: 39 | // 40 | // firstCall := mockObj.EXPECT().SomeMethod(1, "first") 41 | // secondCall := mockObj.EXPECT().SomeMethod(2, "second").After(firstCall) 42 | // mockObj.EXPECT().SomeMethod(3, "third").After(secondCall) 43 | // 44 | // Example of using InOrder to declare expected call order: 45 | // 46 | // gomock.InOrder( 47 | // mockObj.EXPECT().SomeMethod(1, "first"), 48 | // mockObj.EXPECT().SomeMethod(2, "second"), 49 | // mockObj.EXPECT().SomeMethod(3, "third"), 50 | // ) 51 | // 52 | // The standard TestReporter most users will pass to `NewController` is a 53 | // `*testing.T` from the context of the test. Note that this will use the 54 | // standard `t.Error` and `t.Fatal` methods to report what happened in the test. 55 | // In some cases this can leave your testing package in a weird state if global 56 | // state is used since `t.Fatal` is like calling panic in the middle of a 57 | // function. In these cases it is recommended that you pass in your own 58 | // `TestReporter`. 59 | package gomock 60 | -------------------------------------------------------------------------------- /gomock/example_test.go: -------------------------------------------------------------------------------- 1 | package gomock_test 2 | 3 | //go:generate mockgen -destination mock_test.go -package gomock_test -source example_test.go 4 | 5 | import ( 6 | "fmt" 7 | "testing" 8 | "time" 9 | 10 | "github.com/golang/mock/gomock" 11 | ) 12 | 13 | type Foo interface { 14 | Bar(string) string 15 | } 16 | 17 | func ExampleCall_DoAndReturn_latency() { 18 | t := &testing.T{} // provided by test 19 | ctrl := gomock.NewController(t) 20 | mockIndex := NewMockFoo(ctrl) 21 | 22 | mockIndex.EXPECT().Bar(gomock.Any()).DoAndReturn( 23 | func(arg string) string { 24 | time.Sleep(1 * time.Millisecond) 25 | return "I'm sleepy" 26 | }, 27 | ) 28 | 29 | r := mockIndex.Bar("foo") 30 | fmt.Println(r) 31 | // Output: I'm sleepy 32 | } 33 | 34 | func ExampleCall_DoAndReturn_captureArguments() { 35 | t := &testing.T{} // provided by test 36 | ctrl := gomock.NewController(t) 37 | mockIndex := NewMockFoo(ctrl) 38 | var s string 39 | 40 | mockIndex.EXPECT().Bar(gomock.AssignableToTypeOf(s)).DoAndReturn( 41 | func(arg string) interface{} { 42 | s = arg 43 | return "I'm sleepy" 44 | }, 45 | ) 46 | 47 | r := mockIndex.Bar("foo") 48 | fmt.Printf("%s %s", r, s) 49 | // Output: I'm sleepy foo 50 | } 51 | -------------------------------------------------------------------------------- /gomock/internal/mock_gomock/mock_matcher.go: -------------------------------------------------------------------------------- 1 | // Code generated by MockGen. DO NOT EDIT. 2 | // Source: github.com/golang/mock/gomock (interfaces: Matcher) 3 | 4 | // Package mock_gomock is a generated GoMock package. 5 | package mock_gomock 6 | 7 | import ( 8 | reflect "reflect" 9 | 10 | gomock "github.com/golang/mock/gomock" 11 | ) 12 | 13 | // MockMatcher is a mock of Matcher interface. 14 | type MockMatcher struct { 15 | ctrl *gomock.Controller 16 | recorder *MockMatcherMockRecorder 17 | } 18 | 19 | // MockMatcherMockRecorder is the mock recorder for MockMatcher. 20 | type MockMatcherMockRecorder struct { 21 | mock *MockMatcher 22 | } 23 | 24 | // NewMockMatcher creates a new mock instance. 25 | func NewMockMatcher(ctrl *gomock.Controller) *MockMatcher { 26 | mock := &MockMatcher{ctrl: ctrl} 27 | mock.recorder = &MockMatcherMockRecorder{mock} 28 | return mock 29 | } 30 | 31 | // EXPECT returns an object that allows the caller to indicate expected use. 32 | func (m *MockMatcher) EXPECT() *MockMatcherMockRecorder { 33 | return m.recorder 34 | } 35 | 36 | // Matches mocks base method. 37 | func (m *MockMatcher) Matches(arg0 interface{}) bool { 38 | m.ctrl.T.Helper() 39 | ret := m.ctrl.Call(m, "Matches", arg0) 40 | ret0, _ := ret[0].(bool) 41 | return ret0 42 | } 43 | 44 | // Matches indicates an expected call of Matches. 45 | func (mr *MockMatcherMockRecorder) Matches(arg0 interface{}) *gomock.Call { 46 | mr.mock.ctrl.T.Helper() 47 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Matches", reflect.TypeOf((*MockMatcher)(nil).Matches), arg0) 48 | } 49 | 50 | // String mocks base method. 51 | func (m *MockMatcher) String() string { 52 | m.ctrl.T.Helper() 53 | ret := m.ctrl.Call(m, "String") 54 | ret0, _ := ret[0].(string) 55 | return ret0 56 | } 57 | 58 | // String indicates an expected call of String. 59 | func (mr *MockMatcherMockRecorder) String() *gomock.Call { 60 | mr.mock.ctrl.T.Helper() 61 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "String", reflect.TypeOf((*MockMatcher)(nil).String)) 62 | } 63 | -------------------------------------------------------------------------------- /gomock/matchers.go: -------------------------------------------------------------------------------- 1 | // Copyright 2010 Google Inc. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package gomock 16 | 17 | import ( 18 | "fmt" 19 | "reflect" 20 | "strings" 21 | ) 22 | 23 | // A Matcher is a representation of a class of values. 24 | // It is used to represent the valid or expected arguments to a mocked method. 25 | type Matcher interface { 26 | // Matches returns whether x is a match. 27 | Matches(x interface{}) bool 28 | 29 | // String describes what the matcher matches. 30 | String() string 31 | } 32 | 33 | // WantFormatter modifies the given Matcher's String() method to the given 34 | // Stringer. This allows for control on how the "Want" is formatted when 35 | // printing . 36 | func WantFormatter(s fmt.Stringer, m Matcher) Matcher { 37 | type matcher interface { 38 | Matches(x interface{}) bool 39 | } 40 | 41 | return struct { 42 | matcher 43 | fmt.Stringer 44 | }{ 45 | matcher: m, 46 | Stringer: s, 47 | } 48 | } 49 | 50 | // StringerFunc type is an adapter to allow the use of ordinary functions as 51 | // a Stringer. If f is a function with the appropriate signature, 52 | // StringerFunc(f) is a Stringer that calls f. 53 | type StringerFunc func() string 54 | 55 | // String implements fmt.Stringer. 56 | func (f StringerFunc) String() string { 57 | return f() 58 | } 59 | 60 | // GotFormatter is used to better print failure messages. If a matcher 61 | // implements GotFormatter, it will use the result from Got when printing 62 | // the failure message. 63 | type GotFormatter interface { 64 | // Got is invoked with the received value. The result is used when 65 | // printing the failure message. 66 | Got(got interface{}) string 67 | } 68 | 69 | // GotFormatterFunc type is an adapter to allow the use of ordinary 70 | // functions as a GotFormatter. If f is a function with the appropriate 71 | // signature, GotFormatterFunc(f) is a GotFormatter that calls f. 72 | type GotFormatterFunc func(got interface{}) string 73 | 74 | // Got implements GotFormatter. 75 | func (f GotFormatterFunc) Got(got interface{}) string { 76 | return f(got) 77 | } 78 | 79 | // GotFormatterAdapter attaches a GotFormatter to a Matcher. 80 | func GotFormatterAdapter(s GotFormatter, m Matcher) Matcher { 81 | return struct { 82 | GotFormatter 83 | Matcher 84 | }{ 85 | GotFormatter: s, 86 | Matcher: m, 87 | } 88 | } 89 | 90 | type anyMatcher struct{} 91 | 92 | func (anyMatcher) Matches(interface{}) bool { 93 | return true 94 | } 95 | 96 | func (anyMatcher) String() string { 97 | return "is anything" 98 | } 99 | 100 | type eqMatcher struct { 101 | x interface{} 102 | } 103 | 104 | func (e eqMatcher) Matches(x interface{}) bool { 105 | // In case, some value is nil 106 | if e.x == nil || x == nil { 107 | return reflect.DeepEqual(e.x, x) 108 | } 109 | 110 | // Check if types assignable and convert them to common type 111 | x1Val := reflect.ValueOf(e.x) 112 | x2Val := reflect.ValueOf(x) 113 | 114 | if x1Val.Type().AssignableTo(x2Val.Type()) { 115 | x1ValConverted := x1Val.Convert(x2Val.Type()) 116 | return reflect.DeepEqual(x1ValConverted.Interface(), x2Val.Interface()) 117 | } 118 | 119 | return false 120 | } 121 | 122 | func (e eqMatcher) String() string { 123 | return fmt.Sprintf("is equal to %v (%T)", e.x, e.x) 124 | } 125 | 126 | type nilMatcher struct{} 127 | 128 | func (nilMatcher) Matches(x interface{}) bool { 129 | if x == nil { 130 | return true 131 | } 132 | 133 | v := reflect.ValueOf(x) 134 | switch v.Kind() { 135 | case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, 136 | reflect.Ptr, reflect.Slice: 137 | return v.IsNil() 138 | } 139 | 140 | return false 141 | } 142 | 143 | func (nilMatcher) String() string { 144 | return "is nil" 145 | } 146 | 147 | type notMatcher struct { 148 | m Matcher 149 | } 150 | 151 | func (n notMatcher) Matches(x interface{}) bool { 152 | return !n.m.Matches(x) 153 | } 154 | 155 | func (n notMatcher) String() string { 156 | return "not(" + n.m.String() + ")" 157 | } 158 | 159 | type assignableToTypeOfMatcher struct { 160 | targetType reflect.Type 161 | } 162 | 163 | func (m assignableToTypeOfMatcher) Matches(x interface{}) bool { 164 | return reflect.TypeOf(x).AssignableTo(m.targetType) 165 | } 166 | 167 | func (m assignableToTypeOfMatcher) String() string { 168 | return "is assignable to " + m.targetType.Name() 169 | } 170 | 171 | type allMatcher struct { 172 | matchers []Matcher 173 | } 174 | 175 | func (am allMatcher) Matches(x interface{}) bool { 176 | for _, m := range am.matchers { 177 | if !m.Matches(x) { 178 | return false 179 | } 180 | } 181 | return true 182 | } 183 | 184 | func (am allMatcher) String() string { 185 | ss := make([]string, 0, len(am.matchers)) 186 | for _, matcher := range am.matchers { 187 | ss = append(ss, matcher.String()) 188 | } 189 | return strings.Join(ss, "; ") 190 | } 191 | 192 | type lenMatcher struct { 193 | i int 194 | } 195 | 196 | func (m lenMatcher) Matches(x interface{}) bool { 197 | v := reflect.ValueOf(x) 198 | switch v.Kind() { 199 | case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice, reflect.String: 200 | return v.Len() == m.i 201 | default: 202 | return false 203 | } 204 | } 205 | 206 | func (m lenMatcher) String() string { 207 | return fmt.Sprintf("has length %d", m.i) 208 | } 209 | 210 | type inAnyOrderMatcher struct { 211 | x interface{} 212 | } 213 | 214 | func (m inAnyOrderMatcher) Matches(x interface{}) bool { 215 | given, ok := m.prepareValue(x) 216 | if !ok { 217 | return false 218 | } 219 | wanted, ok := m.prepareValue(m.x) 220 | if !ok { 221 | return false 222 | } 223 | 224 | if given.Len() != wanted.Len() { 225 | return false 226 | } 227 | 228 | usedFromGiven := make([]bool, given.Len()) 229 | foundFromWanted := make([]bool, wanted.Len()) 230 | for i := 0; i < wanted.Len(); i++ { 231 | wantedMatcher := Eq(wanted.Index(i).Interface()) 232 | for j := 0; j < given.Len(); j++ { 233 | if usedFromGiven[j] { 234 | continue 235 | } 236 | if wantedMatcher.Matches(given.Index(j).Interface()) { 237 | foundFromWanted[i] = true 238 | usedFromGiven[j] = true 239 | break 240 | } 241 | } 242 | } 243 | 244 | missingFromWanted := 0 245 | for _, found := range foundFromWanted { 246 | if !found { 247 | missingFromWanted++ 248 | } 249 | } 250 | extraInGiven := 0 251 | for _, used := range usedFromGiven { 252 | if !used { 253 | extraInGiven++ 254 | } 255 | } 256 | 257 | return extraInGiven == 0 && missingFromWanted == 0 258 | } 259 | 260 | func (m inAnyOrderMatcher) prepareValue(x interface{}) (reflect.Value, bool) { 261 | xValue := reflect.ValueOf(x) 262 | switch xValue.Kind() { 263 | case reflect.Slice, reflect.Array: 264 | return xValue, true 265 | default: 266 | return reflect.Value{}, false 267 | } 268 | } 269 | 270 | func (m inAnyOrderMatcher) String() string { 271 | return fmt.Sprintf("has the same elements as %v", m.x) 272 | } 273 | 274 | // Constructors 275 | 276 | // All returns a composite Matcher that returns true if and only all of the 277 | // matchers return true. 278 | func All(ms ...Matcher) Matcher { return allMatcher{ms} } 279 | 280 | // Any returns a matcher that always matches. 281 | func Any() Matcher { return anyMatcher{} } 282 | 283 | // Eq returns a matcher that matches on equality. 284 | // 285 | // Example usage: 286 | // Eq(5).Matches(5) // returns true 287 | // Eq(5).Matches(4) // returns false 288 | func Eq(x interface{}) Matcher { return eqMatcher{x} } 289 | 290 | // Len returns a matcher that matches on length. This matcher returns false if 291 | // is compared to a type that is not an array, chan, map, slice, or string. 292 | func Len(i int) Matcher { 293 | return lenMatcher{i} 294 | } 295 | 296 | // Nil returns a matcher that matches if the received value is nil. 297 | // 298 | // Example usage: 299 | // var x *bytes.Buffer 300 | // Nil().Matches(x) // returns true 301 | // x = &bytes.Buffer{} 302 | // Nil().Matches(x) // returns false 303 | func Nil() Matcher { return nilMatcher{} } 304 | 305 | // Not reverses the results of its given child matcher. 306 | // 307 | // Example usage: 308 | // Not(Eq(5)).Matches(4) // returns true 309 | // Not(Eq(5)).Matches(5) // returns false 310 | func Not(x interface{}) Matcher { 311 | if m, ok := x.(Matcher); ok { 312 | return notMatcher{m} 313 | } 314 | return notMatcher{Eq(x)} 315 | } 316 | 317 | // AssignableToTypeOf is a Matcher that matches if the parameter to the mock 318 | // function is assignable to the type of the parameter to this function. 319 | // 320 | // Example usage: 321 | // var s fmt.Stringer = &bytes.Buffer{} 322 | // AssignableToTypeOf(s).Matches(time.Second) // returns true 323 | // AssignableToTypeOf(s).Matches(99) // returns false 324 | // 325 | // var ctx = reflect.TypeOf((*context.Context)(nil)).Elem() 326 | // AssignableToTypeOf(ctx).Matches(context.Background()) // returns true 327 | func AssignableToTypeOf(x interface{}) Matcher { 328 | if xt, ok := x.(reflect.Type); ok { 329 | return assignableToTypeOfMatcher{xt} 330 | } 331 | return assignableToTypeOfMatcher{reflect.TypeOf(x)} 332 | } 333 | 334 | // InAnyOrder is a Matcher that returns true for collections of the same elements ignoring the order. 335 | // 336 | // Example usage: 337 | // InAnyOrder([]int{1, 2, 3}).Matches([]int{1, 3, 2}) // returns true 338 | // InAnyOrder([]int{1, 2, 3}).Matches([]int{1, 2}) // returns false 339 | func InAnyOrder(x interface{}) Matcher { 340 | return inAnyOrderMatcher{x} 341 | } 342 | -------------------------------------------------------------------------------- /gomock/matchers_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2010 Google Inc. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package gomock_test 16 | 17 | //go:generate mockgen -destination internal/mock_gomock/mock_matcher.go github.com/golang/mock/gomock Matcher 18 | 19 | import ( 20 | "context" 21 | "errors" 22 | "reflect" 23 | "testing" 24 | 25 | "github.com/golang/mock/gomock" 26 | "github.com/golang/mock/gomock/internal/mock_gomock" 27 | ) 28 | 29 | type A []string 30 | 31 | func TestMatchers(t *testing.T) { 32 | type e interface{} 33 | tests := []struct { 34 | name string 35 | matcher gomock.Matcher 36 | yes, no []e 37 | }{ 38 | {"test Any", gomock.Any(), []e{3, nil, "foo"}, nil}, 39 | {"test All", gomock.Eq(4), []e{4}, []e{3, "blah", nil, int64(4)}}, 40 | {"test Nil", gomock.Nil(), 41 | []e{nil, (error)(nil), (chan bool)(nil), (*int)(nil)}, 42 | []e{"", 0, make(chan bool), errors.New("err"), new(int)}}, 43 | {"test Not", gomock.Not(gomock.Eq(4)), []e{3, "blah", nil, int64(4)}, []e{4}}, 44 | {"test All", gomock.All(gomock.Any(), gomock.Eq(4)), []e{4}, []e{3, "blah", nil, int64(4)}}, 45 | {"test Len", gomock.Len(2), 46 | []e{[]int{1, 2}, "ab", map[string]int{"a": 0, "b": 1}, [2]string{"a", "b"}}, 47 | []e{[]int{1}, "a", 42, 42.0, false, [1]string{"a"}}, 48 | }, 49 | {"test assignable types", gomock.Eq(A{"a", "b"}), 50 | []e{[]string{"a", "b"}, A{"a", "b"}}, 51 | []e{[]string{"a"}, A{"b"}}, 52 | }, 53 | } 54 | for _, tt := range tests { 55 | t.Run(tt.name, func(t *testing.T) { 56 | for _, x := range tt.yes { 57 | if !tt.matcher.Matches(x) { 58 | t.Errorf(`"%v %s": got false, want true.`, x, tt.matcher) 59 | } 60 | } 61 | for _, x := range tt.no { 62 | if tt.matcher.Matches(x) { 63 | t.Errorf(`"%v %s": got true, want false.`, x, tt.matcher) 64 | } 65 | } 66 | }) 67 | } 68 | } 69 | 70 | // A more thorough test of notMatcher 71 | func TestNotMatcher(t *testing.T) { 72 | ctrl := gomock.NewController(t) 73 | defer ctrl.Finish() 74 | 75 | mockMatcher := mock_gomock.NewMockMatcher(ctrl) 76 | notMatcher := gomock.Not(mockMatcher) 77 | 78 | mockMatcher.EXPECT().Matches(4).Return(true) 79 | if match := notMatcher.Matches(4); match { 80 | t.Errorf("notMatcher should not match 4") 81 | } 82 | 83 | mockMatcher.EXPECT().Matches(5).Return(false) 84 | if match := notMatcher.Matches(5); !match { 85 | t.Errorf("notMatcher should match 5") 86 | } 87 | } 88 | 89 | type Dog struct { 90 | Breed, Name string 91 | } 92 | 93 | type ctxKey struct{} 94 | 95 | // A thorough test of assignableToTypeOfMatcher 96 | func TestAssignableToTypeOfMatcher(t *testing.T) { 97 | ctrl := gomock.NewController(t) 98 | defer ctrl.Finish() 99 | 100 | aStr := "def" 101 | anotherStr := "ghi" 102 | 103 | if match := gomock.AssignableToTypeOf("abc").Matches(4); match { 104 | t.Errorf(`AssignableToTypeOf("abc") should not match 4`) 105 | } 106 | if match := gomock.AssignableToTypeOf("abc").Matches(&aStr); match { 107 | t.Errorf(`AssignableToTypeOf("abc") should not match &aStr (*string)`) 108 | } 109 | if match := gomock.AssignableToTypeOf("abc").Matches("def"); !match { 110 | t.Errorf(`AssignableToTypeOf("abc") should match "def"`) 111 | } 112 | if match := gomock.AssignableToTypeOf(&aStr).Matches("abc"); match { 113 | t.Errorf(`AssignableToTypeOf(&aStr) should not match "abc"`) 114 | } 115 | if match := gomock.AssignableToTypeOf(&aStr).Matches(&anotherStr); !match { 116 | t.Errorf(`AssignableToTypeOf(&aStr) should match &anotherStr`) 117 | } 118 | if match := gomock.AssignableToTypeOf(0).Matches(4); !match { 119 | t.Errorf(`AssignableToTypeOf(0) should match 4`) 120 | } 121 | if match := gomock.AssignableToTypeOf(0).Matches("def"); match { 122 | t.Errorf(`AssignableToTypeOf(0) should not match "def"`) 123 | } 124 | if match := gomock.AssignableToTypeOf(Dog{}).Matches(&Dog{}); match { 125 | t.Errorf(`AssignableToTypeOf(Dog{}) should not match &Dog{}`) 126 | } 127 | if match := gomock.AssignableToTypeOf(Dog{}).Matches(Dog{Breed: "pug", Name: "Fido"}); !match { 128 | t.Errorf(`AssignableToTypeOf(Dog{}) should match Dog{Breed: "pug", Name: "Fido"}`) 129 | } 130 | if match := gomock.AssignableToTypeOf(&Dog{}).Matches(Dog{}); match { 131 | t.Errorf(`AssignableToTypeOf(&Dog{}) should not match Dog{}`) 132 | } 133 | if match := gomock.AssignableToTypeOf(&Dog{}).Matches(&Dog{Breed: "pug", Name: "Fido"}); !match { 134 | t.Errorf(`AssignableToTypeOf(&Dog{}) should match &Dog{Breed: "pug", Name: "Fido"}`) 135 | } 136 | 137 | ctxInterface := reflect.TypeOf((*context.Context)(nil)).Elem() 138 | if match := gomock.AssignableToTypeOf(ctxInterface).Matches(context.Background()); !match { 139 | t.Errorf(`AssignableToTypeOf(context.Context) should not match context.Background()`) 140 | } 141 | 142 | ctxWithValue := context.WithValue(context.Background(), ctxKey{}, "val") 143 | if match := gomock.AssignableToTypeOf(ctxInterface).Matches(ctxWithValue); !match { 144 | t.Errorf(`AssignableToTypeOf(context.Context) should not match ctxWithValue`) 145 | } 146 | } 147 | 148 | func TestInAnyOrder(t *testing.T) { 149 | tests := []struct { 150 | name string 151 | wanted interface{} 152 | given interface{} 153 | wantMatch bool 154 | }{ 155 | { 156 | name: "match for equal slices", 157 | wanted: []int{1, 2, 3}, 158 | given: []int{1, 2, 3}, 159 | wantMatch: true, 160 | }, 161 | { 162 | name: "match for slices with same elements of different order", 163 | wanted: []int{1, 2, 3}, 164 | given: []int{1, 3, 2}, 165 | wantMatch: true, 166 | }, 167 | { 168 | name: "not match for slices with different elements", 169 | wanted: []int{1, 2, 3}, 170 | given: []int{1, 2, 4}, 171 | wantMatch: false, 172 | }, 173 | { 174 | name: "not match for slices with missing elements", 175 | wanted: []int{1, 2, 3}, 176 | given: []int{1, 2}, 177 | wantMatch: false, 178 | }, 179 | { 180 | name: "not match for slices with extra elements", 181 | wanted: []int{1, 2, 3}, 182 | given: []int{1, 2, 3, 4}, 183 | wantMatch: false, 184 | }, 185 | { 186 | name: "match for empty slices", 187 | wanted: []int{}, 188 | given: []int{}, 189 | wantMatch: true, 190 | }, 191 | { 192 | name: "not match for equal slices of different types", 193 | wanted: []float64{1, 2, 3}, 194 | given: []int{1, 2, 3}, 195 | wantMatch: false, 196 | }, 197 | { 198 | name: "match for equal arrays", 199 | wanted: [3]int{1, 2, 3}, 200 | given: [3]int{1, 2, 3}, 201 | wantMatch: true, 202 | }, 203 | { 204 | name: "match for equal arrays of different order", 205 | wanted: [3]int{1, 2, 3}, 206 | given: [3]int{1, 3, 2}, 207 | wantMatch: true, 208 | }, 209 | { 210 | name: "not match for arrays of different elements", 211 | wanted: [3]int{1, 2, 3}, 212 | given: [3]int{1, 2, 4}, 213 | wantMatch: false, 214 | }, 215 | { 216 | name: "not match for arrays with extra elements", 217 | wanted: [3]int{1, 2, 3}, 218 | given: [4]int{1, 2, 3, 4}, 219 | wantMatch: false, 220 | }, 221 | { 222 | name: "not match for arrays with missing elements", 223 | wanted: [3]int{1, 2, 3}, 224 | given: [2]int{1, 2}, 225 | wantMatch: false, 226 | }, 227 | { 228 | name: "not match for equal strings", // matcher shouldn't treat strings as collections 229 | wanted: "123", 230 | given: "123", 231 | wantMatch: false, 232 | }, 233 | { 234 | name: "not match if x type is not iterable", 235 | wanted: 123, 236 | given: []int{123}, 237 | wantMatch: false, 238 | }, 239 | { 240 | name: "not match if in type is not iterable", 241 | wanted: []int{123}, 242 | given: 123, 243 | wantMatch: false, 244 | }, 245 | { 246 | name: "not match if both are not iterable", 247 | wanted: 123, 248 | given: 123, 249 | wantMatch: false, 250 | }, 251 | { 252 | name: "match for equal slices with unhashable elements", 253 | wanted: [][]int{{1}, {1, 2}, {1, 2, 3}}, 254 | given: [][]int{{1}, {1, 2}, {1, 2, 3}}, 255 | wantMatch: true, 256 | }, 257 | { 258 | name: "match for equal slices with unhashable elements of different order", 259 | wanted: [][]int{{1}, {1, 2, 3}, {1, 2}}, 260 | given: [][]int{{1}, {1, 2}, {1, 2, 3}}, 261 | wantMatch: true, 262 | }, 263 | { 264 | name: "not match for different slices with unhashable elements", 265 | wanted: [][]int{{1}, {1, 2, 3}, {1, 2}}, 266 | given: [][]int{{1}, {1, 2, 4}, {1, 3}}, 267 | wantMatch: false, 268 | }, 269 | { 270 | name: "not match for unhashable missing elements", 271 | wanted: [][]int{{1}, {1, 2}, {1, 2, 3}}, 272 | given: [][]int{{1}, {1, 2}}, 273 | wantMatch: false, 274 | }, 275 | { 276 | name: "not match for unhashable extra elements", 277 | wanted: [][]int{{1}, {1, 2}}, 278 | given: [][]int{{1}, {1, 2}, {1, 2, 3}}, 279 | wantMatch: false, 280 | }, 281 | { 282 | name: "match for equal slices of assignable types", 283 | wanted: [][]string{{"a", "b"}}, 284 | given: []A{{"a", "b"}}, 285 | wantMatch: true, 286 | }, 287 | } 288 | for _, tt := range tests { 289 | t.Run(tt.name, func(t *testing.T) { 290 | if got := gomock.InAnyOrder(tt.wanted).Matches(tt.given); got != tt.wantMatch { 291 | t.Errorf("got = %v, wantMatch %v", got, tt.wantMatch) 292 | } 293 | }) 294 | } 295 | } 296 | -------------------------------------------------------------------------------- /gomock/mock_test.go: -------------------------------------------------------------------------------- 1 | // Code generated by MockGen. DO NOT EDIT. 2 | // Source: example_test.go 3 | 4 | // Package gomock_test is a generated GoMock package. 5 | package gomock_test 6 | 7 | import ( 8 | reflect "reflect" 9 | 10 | "github.com/golang/mock/gomock" 11 | ) 12 | 13 | // MockFoo is a mock of Foo interface. 14 | type MockFoo struct { 15 | ctrl *gomock.Controller 16 | recorder *MockFooMockRecorder 17 | } 18 | 19 | // MockFooMockRecorder is the mock recorder for MockFoo. 20 | type MockFooMockRecorder struct { 21 | mock *MockFoo 22 | } 23 | 24 | // NewMockFoo creates a new mock instance. 25 | func NewMockFoo(ctrl *gomock.Controller) *MockFoo { 26 | mock := &MockFoo{ctrl: ctrl} 27 | mock.recorder = &MockFooMockRecorder{mock} 28 | return mock 29 | } 30 | 31 | // EXPECT returns an object that allows the caller to indicate expected use. 32 | func (m *MockFoo) EXPECT() *MockFooMockRecorder { 33 | return m.recorder 34 | } 35 | 36 | // Bar mocks base method. 37 | func (m *MockFoo) Bar(arg0 string) string { 38 | m.ctrl.T.Helper() 39 | ret := m.ctrl.Call(m, "Bar", arg0) 40 | ret0, _ := ret[0].(string) 41 | return ret0 42 | } 43 | 44 | // Bar indicates an expected call of Bar. 45 | func (mr *MockFooMockRecorder) Bar(arg0 interface{}) *gomock.Call { 46 | mr.mock.ctrl.T.Helper() 47 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Bar", reflect.TypeOf((*MockFoo)(nil).Bar), arg0) 48 | } 49 | -------------------------------------------------------------------------------- /mockgen/generic_go118.go: -------------------------------------------------------------------------------- 1 | // Copyright 2022 Google LLC 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // See the License for the specific language governing permissions and 6 | // limitations under the License. 7 | 8 | //go:build go1.18 9 | // +build go1.18 10 | 11 | package main 12 | 13 | import ( 14 | "go/ast" 15 | "strings" 16 | 17 | "github.com/golang/mock/mockgen/model" 18 | ) 19 | 20 | func getTypeSpecTypeParams(ts *ast.TypeSpec) []*ast.Field { 21 | if ts == nil || ts.TypeParams == nil { 22 | return nil 23 | } 24 | return ts.TypeParams.List 25 | } 26 | 27 | func (p *fileParser) parseGenericType(pkg string, typ ast.Expr, tps map[string]bool) (model.Type, error) { 28 | switch v := typ.(type) { 29 | case *ast.IndexExpr: 30 | m, err := p.parseType(pkg, v.X, tps) 31 | if err != nil { 32 | return nil, err 33 | } 34 | nm, ok := m.(*model.NamedType) 35 | if !ok { 36 | return m, nil 37 | } 38 | t, err := p.parseType(pkg, v.Index, tps) 39 | if err != nil { 40 | return nil, err 41 | } 42 | nm.TypeParams = &model.TypeParametersType{TypeParameters: []model.Type{t}} 43 | return m, nil 44 | case *ast.IndexListExpr: 45 | m, err := p.parseType(pkg, v.X, tps) 46 | if err != nil { 47 | return nil, err 48 | } 49 | nm, ok := m.(*model.NamedType) 50 | if !ok { 51 | return m, nil 52 | } 53 | var ts []model.Type 54 | for _, expr := range v.Indices { 55 | t, err := p.parseType(pkg, expr, tps) 56 | if err != nil { 57 | return nil, err 58 | } 59 | ts = append(ts, t) 60 | } 61 | nm.TypeParams = &model.TypeParametersType{TypeParameters: ts} 62 | return m, nil 63 | } 64 | return nil, nil 65 | } 66 | 67 | func getIdentTypeParams(decl interface{}) string { 68 | if decl == nil { 69 | return "" 70 | } 71 | ts, ok := decl.(*ast.TypeSpec) 72 | if !ok { 73 | return "" 74 | } 75 | if ts.TypeParams == nil || len(ts.TypeParams.List) == 0 { 76 | return "" 77 | } 78 | var sb strings.Builder 79 | sb.WriteString("[") 80 | for i, v := range ts.TypeParams.List { 81 | if i != 0 { 82 | sb.WriteString(", ") 83 | } 84 | sb.WriteString(v.Names[0].Name) 85 | } 86 | sb.WriteString("]") 87 | return sb.String() 88 | } 89 | -------------------------------------------------------------------------------- /mockgen/generic_notgo118.go: -------------------------------------------------------------------------------- 1 | // Copyright 2022 Google LLC 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | //go:build !go1.18 16 | // +build !go1.18 17 | 18 | package main 19 | 20 | import ( 21 | "go/ast" 22 | 23 | "github.com/golang/mock/mockgen/model" 24 | ) 25 | 26 | func getTypeSpecTypeParams(ts *ast.TypeSpec) []*ast.Field { 27 | return nil 28 | } 29 | 30 | func (p *fileParser) parseGenericType(pkg string, typ ast.Expr, tps map[string]bool) (model.Type, error) { 31 | return nil, nil 32 | } 33 | 34 | func getIdentTypeParams(decl interface{}) string { 35 | return "" 36 | } 37 | -------------------------------------------------------------------------------- /mockgen/internal/tests/aux_imports_embedded_interface/README.md: -------------------------------------------------------------------------------- 1 | # Embedded Interfaces in aux_files 2 | 3 | Embedded interfaces in `aux_files` generate `unknown embedded interface XXX` errors. 4 | See below for example of the problem: 5 | 6 | ```go 7 | // source 8 | import ( 9 | alias "some.org/package/imported" 10 | ) 11 | 12 | type Source interface { 13 | alias.Foreign 14 | } 15 | ``` 16 | 17 | ```go 18 | // some.org/package/imported 19 | type Foreign interface { 20 | Embedded 21 | } 22 | 23 | type Embedded interface {} 24 | ``` 25 | 26 | Attempting to generate a mock will result in an `unknown embedded interface Embedded`. 27 | The issue is that the `fileParser` stores `auxInterfaces` underneath the package name 28 | explicitly specified in the `aux_files` flag. 29 | 30 | In the `parseInterface` method, there is an incorrect assumption about an embedded interface 31 | always being in the source file. 32 | 33 | ```go 34 | case *ast.Ident: 35 | // Embedded interface in this package. 36 | ei := p.auxInterfaces[""][v.String()] 37 | if ei == nil { 38 | return nil, p.errorf(v.Pos(), "unknown embedded interface %s", v.String()) 39 | } 40 | ``` 41 | -------------------------------------------------------------------------------- /mockgen/internal/tests/aux_imports_embedded_interface/bugreport.go: -------------------------------------------------------------------------------- 1 | package bugreport 2 | 3 | //go:generate mockgen -aux_files faux=faux/faux.go -destination bugreport_mock.go -package bugreport -source=bugreport.go Example 4 | 5 | import ( 6 | "log" 7 | 8 | "github.com/golang/mock/mockgen/internal/tests/aux_imports_embedded_interface/faux" 9 | ) 10 | 11 | // Source is an interface w/ an embedded foreign interface 12 | type Source interface { 13 | faux.Foreign 14 | } 15 | 16 | func CallForeignMethod(s Source) { 17 | log.Println(s.Method()) 18 | } 19 | -------------------------------------------------------------------------------- /mockgen/internal/tests/aux_imports_embedded_interface/bugreport_mock.go: -------------------------------------------------------------------------------- 1 | // Code generated by MockGen. DO NOT EDIT. 2 | // Source: bugreport.go 3 | 4 | // Package bugreport is a generated GoMock package. 5 | package bugreport 6 | 7 | import ( 8 | reflect "reflect" 9 | 10 | gomock "github.com/golang/mock/gomock" 11 | faux "github.com/golang/mock/mockgen/internal/tests/aux_imports_embedded_interface/faux" 12 | ) 13 | 14 | // MockSource is a mock of Source interface. 15 | type MockSource struct { 16 | ctrl *gomock.Controller 17 | recorder *MockSourceMockRecorder 18 | } 19 | 20 | // MockSourceMockRecorder is the mock recorder for MockSource. 21 | type MockSourceMockRecorder struct { 22 | mock *MockSource 23 | } 24 | 25 | // NewMockSource creates a new mock instance. 26 | func NewMockSource(ctrl *gomock.Controller) *MockSource { 27 | mock := &MockSource{ctrl: ctrl} 28 | mock.recorder = &MockSourceMockRecorder{mock} 29 | return mock 30 | } 31 | 32 | // EXPECT returns an object that allows the caller to indicate expected use. 33 | func (m *MockSource) EXPECT() *MockSourceMockRecorder { 34 | return m.recorder 35 | } 36 | 37 | // Error mocks base method. 38 | func (m *MockSource) Error() string { 39 | m.ctrl.T.Helper() 40 | ret := m.ctrl.Call(m, "Error") 41 | ret0, _ := ret[0].(string) 42 | return ret0 43 | } 44 | 45 | // Error indicates an expected call of Error. 46 | func (mr *MockSourceMockRecorder) Error() *gomock.Call { 47 | mr.mock.ctrl.T.Helper() 48 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Error", reflect.TypeOf((*MockSource)(nil).Error)) 49 | } 50 | 51 | // Method mocks base method. 52 | func (m *MockSource) Method() faux.Return { 53 | m.ctrl.T.Helper() 54 | ret := m.ctrl.Call(m, "Method") 55 | ret0, _ := ret[0].(faux.Return) 56 | return ret0 57 | } 58 | 59 | // Method indicates an expected call of Method. 60 | func (mr *MockSourceMockRecorder) Method() *gomock.Call { 61 | mr.mock.ctrl.T.Helper() 62 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Method", reflect.TypeOf((*MockSource)(nil).Method)) 63 | } 64 | -------------------------------------------------------------------------------- /mockgen/internal/tests/aux_imports_embedded_interface/bugreport_test.go: -------------------------------------------------------------------------------- 1 | package bugreport 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/golang/mock/gomock" 7 | ) 8 | 9 | // TestValidInterface assesses whether or not the generated mock is valid 10 | func TestValidInterface(t *testing.T) { 11 | ctrl := gomock.NewController(t) 12 | defer ctrl.Finish() 13 | 14 | s := NewMockSource(ctrl) 15 | s.EXPECT().Method().Return("") 16 | 17 | CallForeignMethod(s) 18 | } 19 | -------------------------------------------------------------------------------- /mockgen/internal/tests/aux_imports_embedded_interface/faux/faux.go: -------------------------------------------------------------------------------- 1 | package faux 2 | 3 | type Foreign interface { 4 | Method() Return 5 | Embedded 6 | error 7 | } 8 | 9 | type Embedded interface{} 10 | 11 | type Return interface{} 12 | -------------------------------------------------------------------------------- /mockgen/internal/tests/const_array_length/input.go: -------------------------------------------------------------------------------- 1 | package const_length 2 | 3 | import "math" 4 | 5 | //go:generate mockgen -package const_length -destination mock.go -source input.go 6 | 7 | const C = 2 8 | 9 | type I interface { 10 | Foo() [C]int 11 | Bar() [2]int 12 | Baz() [math.MaxInt8]int 13 | Qux() [1 + 2]int 14 | Quux() [(1 + 2)]int 15 | Corge() [math.MaxInt8 - 120]int 16 | } 17 | -------------------------------------------------------------------------------- /mockgen/internal/tests/const_array_length/mock.go: -------------------------------------------------------------------------------- 1 | // Code generated by MockGen. DO NOT EDIT. 2 | // Source: input.go 3 | 4 | // Package const_length is a generated GoMock package. 5 | package const_length 6 | 7 | import ( 8 | reflect "reflect" 9 | 10 | gomock "github.com/golang/mock/gomock" 11 | ) 12 | 13 | // MockI is a mock of I interface. 14 | type MockI struct { 15 | ctrl *gomock.Controller 16 | recorder *MockIMockRecorder 17 | } 18 | 19 | // MockIMockRecorder is the mock recorder for MockI. 20 | type MockIMockRecorder struct { 21 | mock *MockI 22 | } 23 | 24 | // NewMockI creates a new mock instance. 25 | func NewMockI(ctrl *gomock.Controller) *MockI { 26 | mock := &MockI{ctrl: ctrl} 27 | mock.recorder = &MockIMockRecorder{mock} 28 | return mock 29 | } 30 | 31 | // EXPECT returns an object that allows the caller to indicate expected use. 32 | func (m *MockI) EXPECT() *MockIMockRecorder { 33 | return m.recorder 34 | } 35 | 36 | // Bar mocks base method. 37 | func (m *MockI) Bar() [2]int { 38 | m.ctrl.T.Helper() 39 | ret := m.ctrl.Call(m, "Bar") 40 | ret0, _ := ret[0].([2]int) 41 | return ret0 42 | } 43 | 44 | // Bar indicates an expected call of Bar. 45 | func (mr *MockIMockRecorder) Bar() *gomock.Call { 46 | mr.mock.ctrl.T.Helper() 47 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Bar", reflect.TypeOf((*MockI)(nil).Bar)) 48 | } 49 | 50 | // Baz mocks base method. 51 | func (m *MockI) Baz() [127]int { 52 | m.ctrl.T.Helper() 53 | ret := m.ctrl.Call(m, "Baz") 54 | ret0, _ := ret[0].([127]int) 55 | return ret0 56 | } 57 | 58 | // Baz indicates an expected call of Baz. 59 | func (mr *MockIMockRecorder) Baz() *gomock.Call { 60 | mr.mock.ctrl.T.Helper() 61 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Baz", reflect.TypeOf((*MockI)(nil).Baz)) 62 | } 63 | 64 | // Corge mocks base method. 65 | func (m *MockI) Corge() [7]int { 66 | m.ctrl.T.Helper() 67 | ret := m.ctrl.Call(m, "Corge") 68 | ret0, _ := ret[0].([7]int) 69 | return ret0 70 | } 71 | 72 | // Corge indicates an expected call of Corge. 73 | func (mr *MockIMockRecorder) Corge() *gomock.Call { 74 | mr.mock.ctrl.T.Helper() 75 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Corge", reflect.TypeOf((*MockI)(nil).Corge)) 76 | } 77 | 78 | // Foo mocks base method. 79 | func (m *MockI) Foo() [2]int { 80 | m.ctrl.T.Helper() 81 | ret := m.ctrl.Call(m, "Foo") 82 | ret0, _ := ret[0].([2]int) 83 | return ret0 84 | } 85 | 86 | // Foo indicates an expected call of Foo. 87 | func (mr *MockIMockRecorder) Foo() *gomock.Call { 88 | mr.mock.ctrl.T.Helper() 89 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Foo", reflect.TypeOf((*MockI)(nil).Foo)) 90 | } 91 | 92 | // Quux mocks base method. 93 | func (m *MockI) Quux() [3]int { 94 | m.ctrl.T.Helper() 95 | ret := m.ctrl.Call(m, "Quux") 96 | ret0, _ := ret[0].([3]int) 97 | return ret0 98 | } 99 | 100 | // Quux indicates an expected call of Quux. 101 | func (mr *MockIMockRecorder) Quux() *gomock.Call { 102 | mr.mock.ctrl.T.Helper() 103 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Quux", reflect.TypeOf((*MockI)(nil).Quux)) 104 | } 105 | 106 | // Qux mocks base method. 107 | func (m *MockI) Qux() [3]int { 108 | m.ctrl.T.Helper() 109 | ret := m.ctrl.Call(m, "Qux") 110 | ret0, _ := ret[0].([3]int) 111 | return ret0 112 | } 113 | 114 | // Qux indicates an expected call of Qux. 115 | func (mr *MockIMockRecorder) Qux() *gomock.Call { 116 | mr.mock.ctrl.T.Helper() 117 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Qux", reflect.TypeOf((*MockI)(nil).Qux)) 118 | } 119 | -------------------------------------------------------------------------------- /mockgen/internal/tests/copyright_file/input.go: -------------------------------------------------------------------------------- 1 | package empty_interface 2 | 3 | //go:generate mockgen -package empty_interface -destination mock.go -source input.go -copyright_file=mock_copyright_header 4 | 5 | type Empty interface{} 6 | -------------------------------------------------------------------------------- /mockgen/internal/tests/copyright_file/mock.go: -------------------------------------------------------------------------------- 1 | // This is a mock copyright header. 2 | // 3 | // Lorem ipsum dolor sit amet, consectetur adipiscing elit, 4 | // sed do eiusmod tempor incididunt ut labore et dolore magna 5 | // aliqua. Velit ut tortor pretium viverra suspendisse potenti. 6 | // 7 | 8 | // Code generated by MockGen. DO NOT EDIT. 9 | // Source: input.go 10 | 11 | // Package empty_interface is a generated GoMock package. 12 | package empty_interface 13 | 14 | import ( 15 | gomock "github.com/golang/mock/gomock" 16 | ) 17 | 18 | // MockEmpty is a mock of Empty interface. 19 | type MockEmpty struct { 20 | ctrl *gomock.Controller 21 | recorder *MockEmptyMockRecorder 22 | } 23 | 24 | // MockEmptyMockRecorder is the mock recorder for MockEmpty. 25 | type MockEmptyMockRecorder struct { 26 | mock *MockEmpty 27 | } 28 | 29 | // NewMockEmpty creates a new mock instance. 30 | func NewMockEmpty(ctrl *gomock.Controller) *MockEmpty { 31 | mock := &MockEmpty{ctrl: ctrl} 32 | mock.recorder = &MockEmptyMockRecorder{mock} 33 | return mock 34 | } 35 | 36 | // EXPECT returns an object that allows the caller to indicate expected use. 37 | func (m *MockEmpty) EXPECT() *MockEmptyMockRecorder { 38 | return m.recorder 39 | } 40 | -------------------------------------------------------------------------------- /mockgen/internal/tests/copyright_file/mock_copyright_header: -------------------------------------------------------------------------------- 1 | This is a mock copyright header. 2 | 3 | Lorem ipsum dolor sit amet, consectetur adipiscing elit, 4 | sed do eiusmod tempor incididunt ut labore et dolore magna 5 | aliqua. Velit ut tortor pretium viverra suspendisse potenti. 6 | -------------------------------------------------------------------------------- /mockgen/internal/tests/custom_package_name/README.md: -------------------------------------------------------------------------------- 1 | # Tests for custom package names 2 | 3 | This directory contains test for mockgen generating mocks when imported package 4 | name does not match import path suffix. For example, package with name "client" 5 | is located under import path "github.com/golang/mock/mockgen/internal/tests/custom_package_name/client/v1". 6 | 7 | Prior to this patch: 8 | 9 | ```bash 10 | $ go generate greeter/greeter.go 11 | 2018/03/05 22:44:52 Loading input failed: greeter.go:17:11: failed parsing returns: greeter.go:17:14: unknown package "client" 12 | greeter/greeter.go:1: running "mockgen": exit status 1 13 | ``` 14 | 15 | This can be fixed by manually providing `-imports` flag, like `-imports client=github.com/golang/mock/mockgen/internal/tests/custom_package_name/client/v1`. 16 | But, mockgen should be able to automatically resolve package names in such situations. 17 | 18 | With this patch applied: 19 | 20 | ```bash 21 | $ go generate greeter/greeter.go 22 | $ echo $? 23 | 0 24 | ``` 25 | 26 | Mockgen runs successfully, produced output is equal to [greeter_mock_test.go](greeter/greeter_mock_test.go) content. 27 | -------------------------------------------------------------------------------- /mockgen/internal/tests/custom_package_name/client/v1/client.go: -------------------------------------------------------------------------------- 1 | package client 2 | 3 | import "fmt" 4 | 5 | type Client struct{} 6 | 7 | func (c *Client) Greet(in GreetInput) string { 8 | return fmt.Sprintf("Hello, %s!", in.Name) 9 | } 10 | 11 | type GreetInput struct { 12 | Name string 13 | } 14 | -------------------------------------------------------------------------------- /mockgen/internal/tests/custom_package_name/greeter/greeter.go: -------------------------------------------------------------------------------- 1 | package greeter 2 | 3 | //go:generate mockgen -source greeter.go -destination greeter_mock_test.go -package greeter 4 | 5 | import ( 6 | // stdlib import 7 | "fmt" 8 | 9 | // non-matching import suffix and package name 10 | "github.com/golang/mock/mockgen/internal/tests/custom_package_name/client/v1" 11 | 12 | // matching import suffix and package name 13 | "github.com/golang/mock/mockgen/internal/tests/custom_package_name/validator" 14 | ) 15 | 16 | type InputMaker interface { 17 | MakeInput() client.GreetInput 18 | } 19 | 20 | type Greeter struct { 21 | InputMaker InputMaker 22 | Client *client.Client 23 | } 24 | 25 | func (g *Greeter) Greet() (string, error) { 26 | in := g.InputMaker.MakeInput() 27 | if err := validator.Validate(in.Name); err != nil { 28 | return "", fmt.Errorf("validation failed: %v", err) 29 | } 30 | return g.Client.Greet(in), nil 31 | } 32 | -------------------------------------------------------------------------------- /mockgen/internal/tests/custom_package_name/greeter/greeter_mock_test.go: -------------------------------------------------------------------------------- 1 | // Code generated by MockGen. DO NOT EDIT. 2 | // Source: greeter.go 3 | 4 | // Package greeter is a generated GoMock package. 5 | package greeter 6 | 7 | import ( 8 | reflect "reflect" 9 | 10 | gomock "github.com/golang/mock/gomock" 11 | client "github.com/golang/mock/mockgen/internal/tests/custom_package_name/client/v1" 12 | ) 13 | 14 | // MockInputMaker is a mock of InputMaker interface. 15 | type MockInputMaker struct { 16 | ctrl *gomock.Controller 17 | recorder *MockInputMakerMockRecorder 18 | } 19 | 20 | // MockInputMakerMockRecorder is the mock recorder for MockInputMaker. 21 | type MockInputMakerMockRecorder struct { 22 | mock *MockInputMaker 23 | } 24 | 25 | // NewMockInputMaker creates a new mock instance. 26 | func NewMockInputMaker(ctrl *gomock.Controller) *MockInputMaker { 27 | mock := &MockInputMaker{ctrl: ctrl} 28 | mock.recorder = &MockInputMakerMockRecorder{mock} 29 | return mock 30 | } 31 | 32 | // EXPECT returns an object that allows the caller to indicate expected use. 33 | func (m *MockInputMaker) EXPECT() *MockInputMakerMockRecorder { 34 | return m.recorder 35 | } 36 | 37 | // MakeInput mocks base method. 38 | func (m *MockInputMaker) MakeInput() client.GreetInput { 39 | m.ctrl.T.Helper() 40 | ret := m.ctrl.Call(m, "MakeInput") 41 | ret0, _ := ret[0].(client.GreetInput) 42 | return ret0 43 | } 44 | 45 | // MakeInput indicates an expected call of MakeInput. 46 | func (mr *MockInputMakerMockRecorder) MakeInput() *gomock.Call { 47 | mr.mock.ctrl.T.Helper() 48 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "MakeInput", reflect.TypeOf((*MockInputMaker)(nil).MakeInput)) 49 | } 50 | -------------------------------------------------------------------------------- /mockgen/internal/tests/custom_package_name/greeter/greeter_test.go: -------------------------------------------------------------------------------- 1 | package greeter 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/golang/mock/gomock" 7 | "github.com/golang/mock/mockgen/internal/tests/custom_package_name/client/v1" 8 | ) 9 | 10 | func TestGreeter_Greet(t *testing.T) { 11 | ctrl := gomock.NewController(t) 12 | defer ctrl.Finish() 13 | 14 | input := client.GreetInput{ 15 | Name: "Foo", 16 | } 17 | 18 | inputMaker := NewMockInputMaker(ctrl) 19 | inputMaker.EXPECT(). 20 | MakeInput(). 21 | Return(input) 22 | 23 | g := &Greeter{ 24 | InputMaker: inputMaker, 25 | Client: &client.Client{}, 26 | } 27 | 28 | greeting, err := g.Greet() 29 | if err != nil { 30 | t.Fatalf("Unexpected error: %v", err) 31 | } 32 | 33 | expected := "Hello, Foo!" 34 | if greeting != expected { 35 | t.Fatalf("Expected greeting to be %v but got %v", expected, greeting) 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /mockgen/internal/tests/custom_package_name/validator/validate.go: -------------------------------------------------------------------------------- 1 | package validator 2 | 3 | func Validate(s string) error { 4 | return nil 5 | } 6 | -------------------------------------------------------------------------------- /mockgen/internal/tests/dot_imports/input.go: -------------------------------------------------------------------------------- 1 | package dot_imports 2 | 3 | //go:generate mockgen -package dot_imports -destination mock.go -source input.go 4 | 5 | import ( 6 | "bytes" 7 | . "context" 8 | . "net/http" 9 | ) 10 | 11 | type WithDotImports interface { 12 | Method1() Request 13 | Method2() *bytes.Buffer 14 | Method3() Context 15 | } 16 | -------------------------------------------------------------------------------- /mockgen/internal/tests/dot_imports/mock.go: -------------------------------------------------------------------------------- 1 | // Code generated by MockGen. DO NOT EDIT. 2 | // Source: input.go 3 | 4 | // Package dot_imports is a generated GoMock package. 5 | package dot_imports 6 | 7 | import ( 8 | bytes "bytes" 9 | . "context" 10 | . "net/http" 11 | reflect "reflect" 12 | 13 | gomock "github.com/golang/mock/gomock" 14 | ) 15 | 16 | // MockWithDotImports is a mock of WithDotImports interface. 17 | type MockWithDotImports struct { 18 | ctrl *gomock.Controller 19 | recorder *MockWithDotImportsMockRecorder 20 | } 21 | 22 | // MockWithDotImportsMockRecorder is the mock recorder for MockWithDotImports. 23 | type MockWithDotImportsMockRecorder struct { 24 | mock *MockWithDotImports 25 | } 26 | 27 | // NewMockWithDotImports creates a new mock instance. 28 | func NewMockWithDotImports(ctrl *gomock.Controller) *MockWithDotImports { 29 | mock := &MockWithDotImports{ctrl: ctrl} 30 | mock.recorder = &MockWithDotImportsMockRecorder{mock} 31 | return mock 32 | } 33 | 34 | // EXPECT returns an object that allows the caller to indicate expected use. 35 | func (m *MockWithDotImports) EXPECT() *MockWithDotImportsMockRecorder { 36 | return m.recorder 37 | } 38 | 39 | // Method1 mocks base method. 40 | func (m *MockWithDotImports) Method1() Request { 41 | m.ctrl.T.Helper() 42 | ret := m.ctrl.Call(m, "Method1") 43 | ret0, _ := ret[0].(Request) 44 | return ret0 45 | } 46 | 47 | // Method1 indicates an expected call of Method1. 48 | func (mr *MockWithDotImportsMockRecorder) Method1() *gomock.Call { 49 | mr.mock.ctrl.T.Helper() 50 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Method1", reflect.TypeOf((*MockWithDotImports)(nil).Method1)) 51 | } 52 | 53 | // Method2 mocks base method. 54 | func (m *MockWithDotImports) Method2() *bytes.Buffer { 55 | m.ctrl.T.Helper() 56 | ret := m.ctrl.Call(m, "Method2") 57 | ret0, _ := ret[0].(*bytes.Buffer) 58 | return ret0 59 | } 60 | 61 | // Method2 indicates an expected call of Method2. 62 | func (mr *MockWithDotImportsMockRecorder) Method2() *gomock.Call { 63 | mr.mock.ctrl.T.Helper() 64 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Method2", reflect.TypeOf((*MockWithDotImports)(nil).Method2)) 65 | } 66 | 67 | // Method3 mocks base method. 68 | func (m *MockWithDotImports) Method3() Context { 69 | m.ctrl.T.Helper() 70 | ret := m.ctrl.Call(m, "Method3") 71 | ret0, _ := ret[0].(Context) 72 | return ret0 73 | } 74 | 75 | // Method3 indicates an expected call of Method3. 76 | func (mr *MockWithDotImportsMockRecorder) Method3() *gomock.Call { 77 | mr.mock.ctrl.T.Helper() 78 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Method3", reflect.TypeOf((*MockWithDotImports)(nil).Method3)) 79 | } 80 | -------------------------------------------------------------------------------- /mockgen/internal/tests/empty_interface/input.go: -------------------------------------------------------------------------------- 1 | package empty_interface 2 | 3 | //go:generate mockgen -package empty_interface -destination mock.go -source input.go 4 | 5 | type Empty interface{} 6 | -------------------------------------------------------------------------------- /mockgen/internal/tests/empty_interface/mock.go: -------------------------------------------------------------------------------- 1 | // Code generated by MockGen. DO NOT EDIT. 2 | // Source: input.go 3 | 4 | // Package empty_interface is a generated GoMock package. 5 | package empty_interface 6 | 7 | import ( 8 | gomock "github.com/golang/mock/gomock" 9 | ) 10 | 11 | // MockEmpty is a mock of Empty interface. 12 | type MockEmpty struct { 13 | ctrl *gomock.Controller 14 | recorder *MockEmptyMockRecorder 15 | } 16 | 17 | // MockEmptyMockRecorder is the mock recorder for MockEmpty. 18 | type MockEmptyMockRecorder struct { 19 | mock *MockEmpty 20 | } 21 | 22 | // NewMockEmpty creates a new mock instance. 23 | func NewMockEmpty(ctrl *gomock.Controller) *MockEmpty { 24 | mock := &MockEmpty{ctrl: ctrl} 25 | mock.recorder = &MockEmptyMockRecorder{mock} 26 | return mock 27 | } 28 | 29 | // EXPECT returns an object that allows the caller to indicate expected use. 30 | func (m *MockEmpty) EXPECT() *MockEmptyMockRecorder { 31 | return m.recorder 32 | } 33 | -------------------------------------------------------------------------------- /mockgen/internal/tests/extra_import/import.go: -------------------------------------------------------------------------------- 1 | // Package extra_import makes sure output does not import it. See #515. 2 | package extra_import 3 | 4 | //go:generate mockgen -destination mock.go -package extra_import . Foo 5 | 6 | type Message struct { 7 | Text string 8 | } 9 | 10 | type Foo interface { 11 | Bar(channels []string, message chan<- Message) 12 | } 13 | -------------------------------------------------------------------------------- /mockgen/internal/tests/extra_import/mock.go: -------------------------------------------------------------------------------- 1 | // Code generated by MockGen. DO NOT EDIT. 2 | // Source: github.com/golang/mock/mockgen/internal/tests/extra_import (interfaces: Foo) 3 | 4 | // Package extra_import is a generated GoMock package. 5 | package extra_import 6 | 7 | import ( 8 | reflect "reflect" 9 | 10 | gomock "github.com/golang/mock/gomock" 11 | ) 12 | 13 | // MockFoo is a mock of Foo interface. 14 | type MockFoo struct { 15 | ctrl *gomock.Controller 16 | recorder *MockFooMockRecorder 17 | } 18 | 19 | // MockFooMockRecorder is the mock recorder for MockFoo. 20 | type MockFooMockRecorder struct { 21 | mock *MockFoo 22 | } 23 | 24 | // NewMockFoo creates a new mock instance. 25 | func NewMockFoo(ctrl *gomock.Controller) *MockFoo { 26 | mock := &MockFoo{ctrl: ctrl} 27 | mock.recorder = &MockFooMockRecorder{mock} 28 | return mock 29 | } 30 | 31 | // EXPECT returns an object that allows the caller to indicate expected use. 32 | func (m *MockFoo) EXPECT() *MockFooMockRecorder { 33 | return m.recorder 34 | } 35 | 36 | // Bar mocks base method. 37 | func (m *MockFoo) Bar(arg0 []string, arg1 chan<- Message) { 38 | m.ctrl.T.Helper() 39 | m.ctrl.Call(m, "Bar", arg0, arg1) 40 | } 41 | 42 | // Bar indicates an expected call of Bar. 43 | func (mr *MockFooMockRecorder) Bar(arg0, arg1 interface{}) *gomock.Call { 44 | mr.mock.ctrl.T.Helper() 45 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Bar", reflect.TypeOf((*MockFoo)(nil).Bar), arg0, arg1) 46 | } 47 | -------------------------------------------------------------------------------- /mockgen/internal/tests/generated_identifier_conflict/README.md: -------------------------------------------------------------------------------- 1 | # Generated Identifier Conflict 2 | 3 | The generated mock methods use some hardcoded variable/receiver names that can 4 | have conflicts with the argument names that are defined by the code for which 5 | the mock is generated when using the source generation method. 6 | 7 | Example: 8 | 9 | ```go 10 | type Example interface { 11 | Method(_m, _mr, m, mr int) 12 | } 13 | ``` 14 | 15 | ```go 16 | // Method mocks base method 17 | func (_m *MockExample) Method(_m int, _mr int, m int, mr int) { 18 | _m.ctrl.Call(_m, "Method", _m, _mr, m, mr) 19 | } 20 | ``` 21 | 22 | In the above example one of the interface method parameters is called `_m` 23 | but unfortunately the generated receiver name is also called `_m` so the 24 | mock code won't compile. 25 | 26 | The generator has to make sure that generated identifiers (e.g.: the receiver 27 | names) are always different from the arg names that might come from external 28 | sources. 29 | -------------------------------------------------------------------------------- /mockgen/internal/tests/generated_identifier_conflict/bugreport.go: -------------------------------------------------------------------------------- 1 | package bugreport 2 | 3 | //go:generate mockgen -destination bugreport_mock.go -package bugreport -source=bugreport.go 4 | 5 | type Example interface { 6 | // _m and _mr were used by the buggy code: the '_' prefix was there hoping 7 | // that no one will use method argument names starting with '_' reducing 8 | // the chance of collision with generated identifiers. 9 | // m and mr are used by the bugfixed new code, the '_' prefix has been 10 | // removed because the new code generator changes the names of the 11 | // generated identifiers in case they would collide with identifiers 12 | // coming from argument names. 13 | Method(_m, _mr, m, mr int) 14 | 15 | VarargMethod(_s, _x, a, ret int, varargs ...int) 16 | } 17 | -------------------------------------------------------------------------------- /mockgen/internal/tests/generated_identifier_conflict/bugreport_mock.go: -------------------------------------------------------------------------------- 1 | // Code generated by MockGen. DO NOT EDIT. 2 | // Source: bugreport.go 3 | 4 | // Package bugreport is a generated GoMock package. 5 | package bugreport 6 | 7 | import ( 8 | reflect "reflect" 9 | 10 | gomock "github.com/golang/mock/gomock" 11 | ) 12 | 13 | // MockExample is a mock of Example interface. 14 | type MockExample struct { 15 | ctrl *gomock.Controller 16 | recorder *MockExampleMockRecorder 17 | } 18 | 19 | // MockExampleMockRecorder is the mock recorder for MockExample. 20 | type MockExampleMockRecorder struct { 21 | mock *MockExample 22 | } 23 | 24 | // NewMockExample creates a new mock instance. 25 | func NewMockExample(ctrl *gomock.Controller) *MockExample { 26 | mock := &MockExample{ctrl: ctrl} 27 | mock.recorder = &MockExampleMockRecorder{mock} 28 | return mock 29 | } 30 | 31 | // EXPECT returns an object that allows the caller to indicate expected use. 32 | func (m *MockExample) EXPECT() *MockExampleMockRecorder { 33 | return m.recorder 34 | } 35 | 36 | // Method mocks base method. 37 | func (m_2 *MockExample) Method(_m, _mr, m, mr int) { 38 | m_2.ctrl.T.Helper() 39 | m_2.ctrl.Call(m_2, "Method", _m, _mr, m, mr) 40 | } 41 | 42 | // Method indicates an expected call of Method. 43 | func (mr_2 *MockExampleMockRecorder) Method(_m, _mr, m, mr interface{}) *gomock.Call { 44 | mr_2.mock.ctrl.T.Helper() 45 | return mr_2.mock.ctrl.RecordCallWithMethodType(mr_2.mock, "Method", reflect.TypeOf((*MockExample)(nil).Method), _m, _mr, m, mr) 46 | } 47 | 48 | // VarargMethod mocks base method. 49 | func (m *MockExample) VarargMethod(_s, _x, a, ret int, varargs ...int) { 50 | m.ctrl.T.Helper() 51 | varargs_2 := []interface{}{_s, _x, a, ret} 52 | for _, a_2 := range varargs { 53 | varargs_2 = append(varargs_2, a_2) 54 | } 55 | m.ctrl.Call(m, "VarargMethod", varargs_2...) 56 | } 57 | 58 | // VarargMethod indicates an expected call of VarargMethod. 59 | func (mr *MockExampleMockRecorder) VarargMethod(_s, _x, a, ret interface{}, varargs ...interface{}) *gomock.Call { 60 | mr.mock.ctrl.T.Helper() 61 | varargs_2 := append([]interface{}{_s, _x, a, ret}, varargs...) 62 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "VarargMethod", reflect.TypeOf((*MockExample)(nil).VarargMethod), varargs_2...) 63 | } 64 | -------------------------------------------------------------------------------- /mockgen/internal/tests/generated_identifier_conflict/bugreport_test.go: -------------------------------------------------------------------------------- 1 | package bugreport 2 | 3 | import ( 4 | "github.com/golang/mock/gomock" 5 | "testing" 6 | ) 7 | 8 | func TestExample_Method(t *testing.T) { 9 | ctrl := gomock.NewController(t) 10 | m := NewMockExample(ctrl) 11 | m.EXPECT().Method(1, 2, 3, 4) 12 | 13 | m.Method(1, 2, 3, 4) 14 | 15 | ctrl.Finish() 16 | } 17 | 18 | func TestExample_VarargMethod(t *testing.T) { 19 | ctrl := gomock.NewController(t) 20 | m := NewMockExample(ctrl) 21 | m.EXPECT().VarargMethod(1, 2, 3, 4, 6, 7) 22 | 23 | m.VarargMethod(1, 2, 3, 4, 6, 7) 24 | 25 | ctrl.Finish() 26 | } 27 | -------------------------------------------------------------------------------- /mockgen/internal/tests/generics/external.go: -------------------------------------------------------------------------------- 1 | package generics 2 | 3 | import ( 4 | "github.com/golang/mock/mockgen/internal/tests/generics/other" 5 | "golang.org/x/exp/constraints" 6 | ) 7 | 8 | //go:generate mockgen --source=external.go --destination=source/mock_external_test.go --package source 9 | 10 | type ExternalConstraint[I constraints.Integer, F constraints.Float] interface { 11 | One(string) string 12 | Two(I) string 13 | Three(I) F 14 | Four(I) Foo[I, F] 15 | Five(I) Baz[F] 16 | Six(I) *Baz[F] 17 | Seven(I) other.One[I] 18 | Eight(F) other.Two[I, F] 19 | Nine(Iface[I]) 20 | Ten(*I) 21 | } 22 | -------------------------------------------------------------------------------- /mockgen/internal/tests/generics/generics.go: -------------------------------------------------------------------------------- 1 | package generics 2 | 3 | import "github.com/golang/mock/mockgen/internal/tests/generics/other" 4 | 5 | //go:generate mockgen --source=generics.go --destination=source/mock_generics_test.go --package source 6 | ////go:generate mockgen --destination=reflect/mock_test.go --package reflect . Bar,Bar2 7 | 8 | type Bar[T any, R any] interface { 9 | One(string) string 10 | Two(T) string 11 | Three(T) R 12 | Four(T) Foo[T, R] 13 | Five(T) Baz[T] 14 | Six(T) *Baz[T] 15 | Seven(T) other.One[T] 16 | Eight(T) other.Two[T, R] 17 | Nine(Iface[T]) 18 | Ten(*T) 19 | Eleven() (*other.One[T], error) 20 | Twelve() (*other.Two[T, R], error) 21 | Thirteen() (Baz[StructType], error) 22 | Fourteen() (*Foo[StructType, StructType2], error) 23 | Fifteen() (Iface[StructType], error) 24 | Sixteen() (Baz[other.Three], error) 25 | Seventeen() (*Foo[other.Three, other.Four], error) 26 | Eighteen() (Iface[*other.Five], error) 27 | Nineteen() AliasType 28 | } 29 | 30 | type Foo[T any, R any] struct{} 31 | 32 | type Baz[T any] struct{} 33 | 34 | type Iface[T any] interface{} 35 | 36 | type StructType struct{} 37 | 38 | type StructType2 struct{} 39 | 40 | type AliasType Baz[other.Three] 41 | -------------------------------------------------------------------------------- /mockgen/internal/tests/generics/go.mod: -------------------------------------------------------------------------------- 1 | module github.com/golang/mock/mockgen/internal/tests/generics 2 | 3 | go 1.18 4 | 5 | require ( 6 | github.com/golang/mock v1.6.0 7 | golang.org/x/exp v0.0.0-20220428152302-39d4317da171 8 | ) 9 | 10 | replace github.com/golang/mock => ../../../.. 11 | -------------------------------------------------------------------------------- /mockgen/internal/tests/generics/go.sum: -------------------------------------------------------------------------------- 1 | github.com/yuin/goldmark v1.4.1/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= 2 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 3 | golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= 4 | golang.org/x/exp v0.0.0-20220428152302-39d4317da171 h1:TfdoLivD44QwvssI9Sv1xwa5DcL5XQr4au4sZ2F2NV4= 5 | golang.org/x/exp v0.0.0-20220428152302-39d4317da171/go.mod h1:lgLbSvA5ygNOMpwM/9anMpWVlVJ7Z+cHWq/eFuinpGE= 6 | golang.org/x/mod v0.5.1/go.mod h1:5OXOZSfqPIIbmVBIIKWRFfZjPR0E5r58TLhUjH0a2Ro= 7 | golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= 8 | golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= 9 | golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= 10 | golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 11 | golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 12 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 13 | golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 14 | golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 15 | golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 16 | golang.org/x/sys v0.0.0-20211019181941-9d821ace8654/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 17 | golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= 18 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 19 | golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= 20 | golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= 21 | golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 22 | golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= 23 | golang.org/x/tools v0.1.8/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU= 24 | golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 25 | golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 26 | golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 27 | -------------------------------------------------------------------------------- /mockgen/internal/tests/generics/other/other.go: -------------------------------------------------------------------------------- 1 | package other 2 | 3 | type One[T any] struct{} 4 | 5 | type Two[T any, R any] struct{} 6 | 7 | type Three struct{} 8 | 9 | type Four struct{} 10 | 11 | type Five interface{} 12 | -------------------------------------------------------------------------------- /mockgen/internal/tests/generics/source/mock_external_test.go: -------------------------------------------------------------------------------- 1 | // Code generated by MockGen. DO NOT EDIT. 2 | // Source: external.go 3 | 4 | // Package source is a generated GoMock package. 5 | package source 6 | 7 | import ( 8 | reflect "reflect" 9 | 10 | gomock "github.com/golang/mock/gomock" 11 | generics "github.com/golang/mock/mockgen/internal/tests/generics" 12 | other "github.com/golang/mock/mockgen/internal/tests/generics/other" 13 | constraints "golang.org/x/exp/constraints" 14 | ) 15 | 16 | // MockExternalConstraint is a mock of ExternalConstraint interface. 17 | type MockExternalConstraint[I constraints.Integer, F constraints.Float] struct { 18 | ctrl *gomock.Controller 19 | recorder *MockExternalConstraintMockRecorder[I, F] 20 | } 21 | 22 | // MockExternalConstraintMockRecorder is the mock recorder for MockExternalConstraint. 23 | type MockExternalConstraintMockRecorder[I constraints.Integer, F constraints.Float] struct { 24 | mock *MockExternalConstraint[I, F] 25 | } 26 | 27 | // NewMockExternalConstraint creates a new mock instance. 28 | func NewMockExternalConstraint[I constraints.Integer, F constraints.Float](ctrl *gomock.Controller) *MockExternalConstraint[I, F] { 29 | mock := &MockExternalConstraint[I, F]{ctrl: ctrl} 30 | mock.recorder = &MockExternalConstraintMockRecorder[I, F]{mock} 31 | return mock 32 | } 33 | 34 | // EXPECT returns an object that allows the caller to indicate expected use. 35 | func (m *MockExternalConstraint[I, F]) EXPECT() *MockExternalConstraintMockRecorder[I, F] { 36 | return m.recorder 37 | } 38 | 39 | // Eight mocks base method. 40 | func (m *MockExternalConstraint[I, F]) Eight(arg0 F) other.Two[I, F] { 41 | m.ctrl.T.Helper() 42 | ret := m.ctrl.Call(m, "Eight", arg0) 43 | ret0, _ := ret[0].(other.Two[I, F]) 44 | return ret0 45 | } 46 | 47 | // Eight indicates an expected call of Eight. 48 | func (mr *MockExternalConstraintMockRecorder[I, F]) Eight(arg0 interface{}) *gomock.Call { 49 | mr.mock.ctrl.T.Helper() 50 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Eight", reflect.TypeOf((*MockExternalConstraint[I, F])(nil).Eight), arg0) 51 | } 52 | 53 | // Five mocks base method. 54 | func (m *MockExternalConstraint[I, F]) Five(arg0 I) generics.Baz[F] { 55 | m.ctrl.T.Helper() 56 | ret := m.ctrl.Call(m, "Five", arg0) 57 | ret0, _ := ret[0].(generics.Baz[F]) 58 | return ret0 59 | } 60 | 61 | // Five indicates an expected call of Five. 62 | func (mr *MockExternalConstraintMockRecorder[I, F]) Five(arg0 interface{}) *gomock.Call { 63 | mr.mock.ctrl.T.Helper() 64 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Five", reflect.TypeOf((*MockExternalConstraint[I, F])(nil).Five), arg0) 65 | } 66 | 67 | // Four mocks base method. 68 | func (m *MockExternalConstraint[I, F]) Four(arg0 I) generics.Foo[I, F] { 69 | m.ctrl.T.Helper() 70 | ret := m.ctrl.Call(m, "Four", arg0) 71 | ret0, _ := ret[0].(generics.Foo[I, F]) 72 | return ret0 73 | } 74 | 75 | // Four indicates an expected call of Four. 76 | func (mr *MockExternalConstraintMockRecorder[I, F]) Four(arg0 interface{}) *gomock.Call { 77 | mr.mock.ctrl.T.Helper() 78 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Four", reflect.TypeOf((*MockExternalConstraint[I, F])(nil).Four), arg0) 79 | } 80 | 81 | // Nine mocks base method. 82 | func (m *MockExternalConstraint[I, F]) Nine(arg0 generics.Iface[I]) { 83 | m.ctrl.T.Helper() 84 | m.ctrl.Call(m, "Nine", arg0) 85 | } 86 | 87 | // Nine indicates an expected call of Nine. 88 | func (mr *MockExternalConstraintMockRecorder[I, F]) Nine(arg0 interface{}) *gomock.Call { 89 | mr.mock.ctrl.T.Helper() 90 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Nine", reflect.TypeOf((*MockExternalConstraint[I, F])(nil).Nine), arg0) 91 | } 92 | 93 | // One mocks base method. 94 | func (m *MockExternalConstraint[I, F]) One(arg0 string) string { 95 | m.ctrl.T.Helper() 96 | ret := m.ctrl.Call(m, "One", arg0) 97 | ret0, _ := ret[0].(string) 98 | return ret0 99 | } 100 | 101 | // One indicates an expected call of One. 102 | func (mr *MockExternalConstraintMockRecorder[I, F]) One(arg0 interface{}) *gomock.Call { 103 | mr.mock.ctrl.T.Helper() 104 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "One", reflect.TypeOf((*MockExternalConstraint[I, F])(nil).One), arg0) 105 | } 106 | 107 | // Seven mocks base method. 108 | func (m *MockExternalConstraint[I, F]) Seven(arg0 I) other.One[I] { 109 | m.ctrl.T.Helper() 110 | ret := m.ctrl.Call(m, "Seven", arg0) 111 | ret0, _ := ret[0].(other.One[I]) 112 | return ret0 113 | } 114 | 115 | // Seven indicates an expected call of Seven. 116 | func (mr *MockExternalConstraintMockRecorder[I, F]) Seven(arg0 interface{}) *gomock.Call { 117 | mr.mock.ctrl.T.Helper() 118 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Seven", reflect.TypeOf((*MockExternalConstraint[I, F])(nil).Seven), arg0) 119 | } 120 | 121 | // Six mocks base method. 122 | func (m *MockExternalConstraint[I, F]) Six(arg0 I) *generics.Baz[F] { 123 | m.ctrl.T.Helper() 124 | ret := m.ctrl.Call(m, "Six", arg0) 125 | ret0, _ := ret[0].(*generics.Baz[F]) 126 | return ret0 127 | } 128 | 129 | // Six indicates an expected call of Six. 130 | func (mr *MockExternalConstraintMockRecorder[I, F]) Six(arg0 interface{}) *gomock.Call { 131 | mr.mock.ctrl.T.Helper() 132 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Six", reflect.TypeOf((*MockExternalConstraint[I, F])(nil).Six), arg0) 133 | } 134 | 135 | // Ten mocks base method. 136 | func (m *MockExternalConstraint[I, F]) Ten(arg0 *I) { 137 | m.ctrl.T.Helper() 138 | m.ctrl.Call(m, "Ten", arg0) 139 | } 140 | 141 | // Ten indicates an expected call of Ten. 142 | func (mr *MockExternalConstraintMockRecorder[I, F]) Ten(arg0 interface{}) *gomock.Call { 143 | mr.mock.ctrl.T.Helper() 144 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Ten", reflect.TypeOf((*MockExternalConstraint[I, F])(nil).Ten), arg0) 145 | } 146 | 147 | // Three mocks base method. 148 | func (m *MockExternalConstraint[I, F]) Three(arg0 I) F { 149 | m.ctrl.T.Helper() 150 | ret := m.ctrl.Call(m, "Three", arg0) 151 | ret0, _ := ret[0].(F) 152 | return ret0 153 | } 154 | 155 | // Three indicates an expected call of Three. 156 | func (mr *MockExternalConstraintMockRecorder[I, F]) Three(arg0 interface{}) *gomock.Call { 157 | mr.mock.ctrl.T.Helper() 158 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Three", reflect.TypeOf((*MockExternalConstraint[I, F])(nil).Three), arg0) 159 | } 160 | 161 | // Two mocks base method. 162 | func (m *MockExternalConstraint[I, F]) Two(arg0 I) string { 163 | m.ctrl.T.Helper() 164 | ret := m.ctrl.Call(m, "Two", arg0) 165 | ret0, _ := ret[0].(string) 166 | return ret0 167 | } 168 | 169 | // Two indicates an expected call of Two. 170 | func (mr *MockExternalConstraintMockRecorder[I, F]) Two(arg0 interface{}) *gomock.Call { 171 | mr.mock.ctrl.T.Helper() 172 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Two", reflect.TypeOf((*MockExternalConstraint[I, F])(nil).Two), arg0) 173 | } 174 | -------------------------------------------------------------------------------- /mockgen/internal/tests/generics/source/mock_generics_test.go: -------------------------------------------------------------------------------- 1 | // Code generated by MockGen. DO NOT EDIT. 2 | // Source: generics.go 3 | 4 | // Package source is a generated GoMock package. 5 | package source 6 | 7 | import ( 8 | reflect "reflect" 9 | 10 | gomock "github.com/golang/mock/gomock" 11 | generics "github.com/golang/mock/mockgen/internal/tests/generics" 12 | other "github.com/golang/mock/mockgen/internal/tests/generics/other" 13 | ) 14 | 15 | // MockBar is a mock of Bar interface. 16 | type MockBar[T any, R any] struct { 17 | ctrl *gomock.Controller 18 | recorder *MockBarMockRecorder[T, R] 19 | } 20 | 21 | // MockBarMockRecorder is the mock recorder for MockBar. 22 | type MockBarMockRecorder[T any, R any] struct { 23 | mock *MockBar[T, R] 24 | } 25 | 26 | // NewMockBar creates a new mock instance. 27 | func NewMockBar[T any, R any](ctrl *gomock.Controller) *MockBar[T, R] { 28 | mock := &MockBar[T, R]{ctrl: ctrl} 29 | mock.recorder = &MockBarMockRecorder[T, R]{mock} 30 | return mock 31 | } 32 | 33 | // EXPECT returns an object that allows the caller to indicate expected use. 34 | func (m *MockBar[T, R]) EXPECT() *MockBarMockRecorder[T, R] { 35 | return m.recorder 36 | } 37 | 38 | // Eight mocks base method. 39 | func (m *MockBar[T, R]) Eight(arg0 T) other.Two[T, R] { 40 | m.ctrl.T.Helper() 41 | ret := m.ctrl.Call(m, "Eight", arg0) 42 | ret0, _ := ret[0].(other.Two[T, R]) 43 | return ret0 44 | } 45 | 46 | // Eight indicates an expected call of Eight. 47 | func (mr *MockBarMockRecorder[T, R]) Eight(arg0 interface{}) *gomock.Call { 48 | mr.mock.ctrl.T.Helper() 49 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Eight", reflect.TypeOf((*MockBar[T, R])(nil).Eight), arg0) 50 | } 51 | 52 | // Eighteen mocks base method. 53 | func (m *MockBar[T, R]) Eighteen() (generics.Iface[*other.Five], error) { 54 | m.ctrl.T.Helper() 55 | ret := m.ctrl.Call(m, "Eighteen") 56 | ret0, _ := ret[0].(generics.Iface[*other.Five]) 57 | ret1, _ := ret[1].(error) 58 | return ret0, ret1 59 | } 60 | 61 | // Eighteen indicates an expected call of Eighteen. 62 | func (mr *MockBarMockRecorder[T, R]) Eighteen() *gomock.Call { 63 | mr.mock.ctrl.T.Helper() 64 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Eighteen", reflect.TypeOf((*MockBar[T, R])(nil).Eighteen)) 65 | } 66 | 67 | // Eleven mocks base method. 68 | func (m *MockBar[T, R]) Eleven() (*other.One[T], error) { 69 | m.ctrl.T.Helper() 70 | ret := m.ctrl.Call(m, "Eleven") 71 | ret0, _ := ret[0].(*other.One[T]) 72 | ret1, _ := ret[1].(error) 73 | return ret0, ret1 74 | } 75 | 76 | // Eleven indicates an expected call of Eleven. 77 | func (mr *MockBarMockRecorder[T, R]) Eleven() *gomock.Call { 78 | mr.mock.ctrl.T.Helper() 79 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Eleven", reflect.TypeOf((*MockBar[T, R])(nil).Eleven)) 80 | } 81 | 82 | // Fifteen mocks base method. 83 | func (m *MockBar[T, R]) Fifteen() (generics.Iface[generics.StructType], error) { 84 | m.ctrl.T.Helper() 85 | ret := m.ctrl.Call(m, "Fifteen") 86 | ret0, _ := ret[0].(generics.Iface[generics.StructType]) 87 | ret1, _ := ret[1].(error) 88 | return ret0, ret1 89 | } 90 | 91 | // Fifteen indicates an expected call of Fifteen. 92 | func (mr *MockBarMockRecorder[T, R]) Fifteen() *gomock.Call { 93 | mr.mock.ctrl.T.Helper() 94 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Fifteen", reflect.TypeOf((*MockBar[T, R])(nil).Fifteen)) 95 | } 96 | 97 | // Five mocks base method. 98 | func (m *MockBar[T, R]) Five(arg0 T) generics.Baz[T] { 99 | m.ctrl.T.Helper() 100 | ret := m.ctrl.Call(m, "Five", arg0) 101 | ret0, _ := ret[0].(generics.Baz[T]) 102 | return ret0 103 | } 104 | 105 | // Five indicates an expected call of Five. 106 | func (mr *MockBarMockRecorder[T, R]) Five(arg0 interface{}) *gomock.Call { 107 | mr.mock.ctrl.T.Helper() 108 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Five", reflect.TypeOf((*MockBar[T, R])(nil).Five), arg0) 109 | } 110 | 111 | // Four mocks base method. 112 | func (m *MockBar[T, R]) Four(arg0 T) generics.Foo[T, R] { 113 | m.ctrl.T.Helper() 114 | ret := m.ctrl.Call(m, "Four", arg0) 115 | ret0, _ := ret[0].(generics.Foo[T, R]) 116 | return ret0 117 | } 118 | 119 | // Four indicates an expected call of Four. 120 | func (mr *MockBarMockRecorder[T, R]) Four(arg0 interface{}) *gomock.Call { 121 | mr.mock.ctrl.T.Helper() 122 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Four", reflect.TypeOf((*MockBar[T, R])(nil).Four), arg0) 123 | } 124 | 125 | // Fourteen mocks base method. 126 | func (m *MockBar[T, R]) Fourteen() (*generics.Foo[generics.StructType, generics.StructType2], error) { 127 | m.ctrl.T.Helper() 128 | ret := m.ctrl.Call(m, "Fourteen") 129 | ret0, _ := ret[0].(*generics.Foo[generics.StructType, generics.StructType2]) 130 | ret1, _ := ret[1].(error) 131 | return ret0, ret1 132 | } 133 | 134 | // Fourteen indicates an expected call of Fourteen. 135 | func (mr *MockBarMockRecorder[T, R]) Fourteen() *gomock.Call { 136 | mr.mock.ctrl.T.Helper() 137 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Fourteen", reflect.TypeOf((*MockBar[T, R])(nil).Fourteen)) 138 | } 139 | 140 | // Nine mocks base method. 141 | func (m *MockBar[T, R]) Nine(arg0 generics.Iface[T]) { 142 | m.ctrl.T.Helper() 143 | m.ctrl.Call(m, "Nine", arg0) 144 | } 145 | 146 | // Nine indicates an expected call of Nine. 147 | func (mr *MockBarMockRecorder[T, R]) Nine(arg0 interface{}) *gomock.Call { 148 | mr.mock.ctrl.T.Helper() 149 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Nine", reflect.TypeOf((*MockBar[T, R])(nil).Nine), arg0) 150 | } 151 | 152 | // Nineteen mocks base method. 153 | func (m *MockBar[T, R]) Nineteen() generics.AliasType { 154 | m.ctrl.T.Helper() 155 | ret := m.ctrl.Call(m, "Nineteen") 156 | ret0, _ := ret[0].(generics.AliasType) 157 | return ret0 158 | } 159 | 160 | // Nineteen indicates an expected call of Nineteen. 161 | func (mr *MockBarMockRecorder[T, R]) Nineteen() *gomock.Call { 162 | mr.mock.ctrl.T.Helper() 163 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Nineteen", reflect.TypeOf((*MockBar[T, R])(nil).Nineteen)) 164 | } 165 | 166 | // One mocks base method. 167 | func (m *MockBar[T, R]) One(arg0 string) string { 168 | m.ctrl.T.Helper() 169 | ret := m.ctrl.Call(m, "One", arg0) 170 | ret0, _ := ret[0].(string) 171 | return ret0 172 | } 173 | 174 | // One indicates an expected call of One. 175 | func (mr *MockBarMockRecorder[T, R]) One(arg0 interface{}) *gomock.Call { 176 | mr.mock.ctrl.T.Helper() 177 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "One", reflect.TypeOf((*MockBar[T, R])(nil).One), arg0) 178 | } 179 | 180 | // Seven mocks base method. 181 | func (m *MockBar[T, R]) Seven(arg0 T) other.One[T] { 182 | m.ctrl.T.Helper() 183 | ret := m.ctrl.Call(m, "Seven", arg0) 184 | ret0, _ := ret[0].(other.One[T]) 185 | return ret0 186 | } 187 | 188 | // Seven indicates an expected call of Seven. 189 | func (mr *MockBarMockRecorder[T, R]) Seven(arg0 interface{}) *gomock.Call { 190 | mr.mock.ctrl.T.Helper() 191 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Seven", reflect.TypeOf((*MockBar[T, R])(nil).Seven), arg0) 192 | } 193 | 194 | // Seventeen mocks base method. 195 | func (m *MockBar[T, R]) Seventeen() (*generics.Foo[other.Three, other.Four], error) { 196 | m.ctrl.T.Helper() 197 | ret := m.ctrl.Call(m, "Seventeen") 198 | ret0, _ := ret[0].(*generics.Foo[other.Three, other.Four]) 199 | ret1, _ := ret[1].(error) 200 | return ret0, ret1 201 | } 202 | 203 | // Seventeen indicates an expected call of Seventeen. 204 | func (mr *MockBarMockRecorder[T, R]) Seventeen() *gomock.Call { 205 | mr.mock.ctrl.T.Helper() 206 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Seventeen", reflect.TypeOf((*MockBar[T, R])(nil).Seventeen)) 207 | } 208 | 209 | // Six mocks base method. 210 | func (m *MockBar[T, R]) Six(arg0 T) *generics.Baz[T] { 211 | m.ctrl.T.Helper() 212 | ret := m.ctrl.Call(m, "Six", arg0) 213 | ret0, _ := ret[0].(*generics.Baz[T]) 214 | return ret0 215 | } 216 | 217 | // Six indicates an expected call of Six. 218 | func (mr *MockBarMockRecorder[T, R]) Six(arg0 interface{}) *gomock.Call { 219 | mr.mock.ctrl.T.Helper() 220 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Six", reflect.TypeOf((*MockBar[T, R])(nil).Six), arg0) 221 | } 222 | 223 | // Sixteen mocks base method. 224 | func (m *MockBar[T, R]) Sixteen() (generics.Baz[other.Three], error) { 225 | m.ctrl.T.Helper() 226 | ret := m.ctrl.Call(m, "Sixteen") 227 | ret0, _ := ret[0].(generics.Baz[other.Three]) 228 | ret1, _ := ret[1].(error) 229 | return ret0, ret1 230 | } 231 | 232 | // Sixteen indicates an expected call of Sixteen. 233 | func (mr *MockBarMockRecorder[T, R]) Sixteen() *gomock.Call { 234 | mr.mock.ctrl.T.Helper() 235 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Sixteen", reflect.TypeOf((*MockBar[T, R])(nil).Sixteen)) 236 | } 237 | 238 | // Ten mocks base method. 239 | func (m *MockBar[T, R]) Ten(arg0 *T) { 240 | m.ctrl.T.Helper() 241 | m.ctrl.Call(m, "Ten", arg0) 242 | } 243 | 244 | // Ten indicates an expected call of Ten. 245 | func (mr *MockBarMockRecorder[T, R]) Ten(arg0 interface{}) *gomock.Call { 246 | mr.mock.ctrl.T.Helper() 247 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Ten", reflect.TypeOf((*MockBar[T, R])(nil).Ten), arg0) 248 | } 249 | 250 | // Thirteen mocks base method. 251 | func (m *MockBar[T, R]) Thirteen() (generics.Baz[generics.StructType], error) { 252 | m.ctrl.T.Helper() 253 | ret := m.ctrl.Call(m, "Thirteen") 254 | ret0, _ := ret[0].(generics.Baz[generics.StructType]) 255 | ret1, _ := ret[1].(error) 256 | return ret0, ret1 257 | } 258 | 259 | // Thirteen indicates an expected call of Thirteen. 260 | func (mr *MockBarMockRecorder[T, R]) Thirteen() *gomock.Call { 261 | mr.mock.ctrl.T.Helper() 262 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Thirteen", reflect.TypeOf((*MockBar[T, R])(nil).Thirteen)) 263 | } 264 | 265 | // Three mocks base method. 266 | func (m *MockBar[T, R]) Three(arg0 T) R { 267 | m.ctrl.T.Helper() 268 | ret := m.ctrl.Call(m, "Three", arg0) 269 | ret0, _ := ret[0].(R) 270 | return ret0 271 | } 272 | 273 | // Three indicates an expected call of Three. 274 | func (mr *MockBarMockRecorder[T, R]) Three(arg0 interface{}) *gomock.Call { 275 | mr.mock.ctrl.T.Helper() 276 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Three", reflect.TypeOf((*MockBar[T, R])(nil).Three), arg0) 277 | } 278 | 279 | // Twelve mocks base method. 280 | func (m *MockBar[T, R]) Twelve() (*other.Two[T, R], error) { 281 | m.ctrl.T.Helper() 282 | ret := m.ctrl.Call(m, "Twelve") 283 | ret0, _ := ret[0].(*other.Two[T, R]) 284 | ret1, _ := ret[1].(error) 285 | return ret0, ret1 286 | } 287 | 288 | // Twelve indicates an expected call of Twelve. 289 | func (mr *MockBarMockRecorder[T, R]) Twelve() *gomock.Call { 290 | mr.mock.ctrl.T.Helper() 291 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Twelve", reflect.TypeOf((*MockBar[T, R])(nil).Twelve)) 292 | } 293 | 294 | // Two mocks base method. 295 | func (m *MockBar[T, R]) Two(arg0 T) string { 296 | m.ctrl.T.Helper() 297 | ret := m.ctrl.Call(m, "Two", arg0) 298 | ret0, _ := ret[0].(string) 299 | return ret0 300 | } 301 | 302 | // Two indicates an expected call of Two. 303 | func (mr *MockBarMockRecorder[T, R]) Two(arg0 interface{}) *gomock.Call { 304 | mr.mock.ctrl.T.Helper() 305 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Two", reflect.TypeOf((*MockBar[T, R])(nil).Two), arg0) 306 | } 307 | 308 | // MockIface is a mock of Iface interface. 309 | type MockIface[T any] struct { 310 | ctrl *gomock.Controller 311 | recorder *MockIfaceMockRecorder[T] 312 | } 313 | 314 | // MockIfaceMockRecorder is the mock recorder for MockIface. 315 | type MockIfaceMockRecorder[T any] struct { 316 | mock *MockIface[T] 317 | } 318 | 319 | // NewMockIface creates a new mock instance. 320 | func NewMockIface[T any](ctrl *gomock.Controller) *MockIface[T] { 321 | mock := &MockIface[T]{ctrl: ctrl} 322 | mock.recorder = &MockIfaceMockRecorder[T]{mock} 323 | return mock 324 | } 325 | 326 | // EXPECT returns an object that allows the caller to indicate expected use. 327 | func (m *MockIface[T]) EXPECT() *MockIfaceMockRecorder[T] { 328 | return m.recorder 329 | } 330 | -------------------------------------------------------------------------------- /mockgen/internal/tests/import_embedded_interface/bugreport.go: -------------------------------------------------------------------------------- 1 | // Copyright 2020 Google Inc. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package bugreport 16 | 17 | //go:generate mockgen -destination bugreport_mock.go -package bugreport -source=bugreport.go 18 | 19 | import ( 20 | "log" 21 | 22 | "github.com/golang/mock/mockgen/internal/tests/import_embedded_interface/ersatz" 23 | "github.com/golang/mock/mockgen/internal/tests/import_embedded_interface/faux" 24 | ) 25 | 26 | // Source is an interface w/ an embedded foreign interface 27 | type Source interface { 28 | ersatz.Embedded 29 | faux.Foreign 30 | error 31 | Foo 32 | } 33 | 34 | func CallForeignMethod(s Source) { 35 | log.Println(s.Ersatz()) 36 | log.Println(s.OtherErsatz()) 37 | } 38 | -------------------------------------------------------------------------------- /mockgen/internal/tests/import_embedded_interface/bugreport_mock.go: -------------------------------------------------------------------------------- 1 | // Code generated by MockGen. DO NOT EDIT. 2 | // Source: bugreport.go 3 | 4 | // Package bugreport is a generated GoMock package. 5 | package bugreport 6 | 7 | import ( 8 | reflect "reflect" 9 | 10 | gomock "github.com/golang/mock/gomock" 11 | ersatz "github.com/golang/mock/mockgen/internal/tests/import_embedded_interface/ersatz" 12 | ersatz0 "github.com/golang/mock/mockgen/internal/tests/import_embedded_interface/other/ersatz" 13 | ) 14 | 15 | // MockSource is a mock of Source interface. 16 | type MockSource struct { 17 | ctrl *gomock.Controller 18 | recorder *MockSourceMockRecorder 19 | } 20 | 21 | // MockSourceMockRecorder is the mock recorder for MockSource. 22 | type MockSourceMockRecorder struct { 23 | mock *MockSource 24 | } 25 | 26 | // NewMockSource creates a new mock instance. 27 | func NewMockSource(ctrl *gomock.Controller) *MockSource { 28 | mock := &MockSource{ctrl: ctrl} 29 | mock.recorder = &MockSourceMockRecorder{mock} 30 | return mock 31 | } 32 | 33 | // EXPECT returns an object that allows the caller to indicate expected use. 34 | func (m *MockSource) EXPECT() *MockSourceMockRecorder { 35 | return m.recorder 36 | } 37 | 38 | // Bar mocks base method. 39 | func (m *MockSource) Bar() Baz { 40 | m.ctrl.T.Helper() 41 | ret := m.ctrl.Call(m, "Bar") 42 | ret0, _ := ret[0].(Baz) 43 | return ret0 44 | } 45 | 46 | // Bar indicates an expected call of Bar. 47 | func (mr *MockSourceMockRecorder) Bar() *gomock.Call { 48 | mr.mock.ctrl.T.Helper() 49 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Bar", reflect.TypeOf((*MockSource)(nil).Bar)) 50 | } 51 | 52 | // Error mocks base method. 53 | func (m *MockSource) Error() string { 54 | m.ctrl.T.Helper() 55 | ret := m.ctrl.Call(m, "Error") 56 | ret0, _ := ret[0].(string) 57 | return ret0 58 | } 59 | 60 | // Error indicates an expected call of Error. 61 | func (mr *MockSourceMockRecorder) Error() *gomock.Call { 62 | mr.mock.ctrl.T.Helper() 63 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Error", reflect.TypeOf((*MockSource)(nil).Error)) 64 | } 65 | 66 | // Ersatz mocks base method. 67 | func (m *MockSource) Ersatz() ersatz.Return { 68 | m.ctrl.T.Helper() 69 | ret := m.ctrl.Call(m, "Ersatz") 70 | ret0, _ := ret[0].(ersatz.Return) 71 | return ret0 72 | } 73 | 74 | // Ersatz indicates an expected call of Ersatz. 75 | func (mr *MockSourceMockRecorder) Ersatz() *gomock.Call { 76 | mr.mock.ctrl.T.Helper() 77 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Ersatz", reflect.TypeOf((*MockSource)(nil).Ersatz)) 78 | } 79 | 80 | // OtherErsatz mocks base method. 81 | func (m *MockSource) OtherErsatz() ersatz0.Return { 82 | m.ctrl.T.Helper() 83 | ret := m.ctrl.Call(m, "OtherErsatz") 84 | ret0, _ := ret[0].(ersatz0.Return) 85 | return ret0 86 | } 87 | 88 | // OtherErsatz indicates an expected call of OtherErsatz. 89 | func (mr *MockSourceMockRecorder) OtherErsatz() *gomock.Call { 90 | mr.mock.ctrl.T.Helper() 91 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "OtherErsatz", reflect.TypeOf((*MockSource)(nil).OtherErsatz)) 92 | } 93 | -------------------------------------------------------------------------------- /mockgen/internal/tests/import_embedded_interface/bugreport_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2020 Google Inc. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | package bugreport 15 | 16 | import ( 17 | "testing" 18 | 19 | "github.com/golang/mock/gomock" 20 | ) 21 | 22 | // TestValidInterface assesses whether or not the generated mock is valid 23 | func TestValidInterface(t *testing.T) { 24 | ctrl := gomock.NewController(t) 25 | defer ctrl.Finish() 26 | 27 | s := NewMockSource(ctrl) 28 | s.EXPECT().Ersatz().Return("") 29 | s.EXPECT().OtherErsatz().Return("") 30 | CallForeignMethod(s) 31 | } 32 | -------------------------------------------------------------------------------- /mockgen/internal/tests/import_embedded_interface/ersatz/ersatz.go: -------------------------------------------------------------------------------- 1 | // Copyright 2020 Google Inc. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | package ersatz 15 | 16 | type Embedded interface { 17 | Ersatz() Return 18 | } 19 | 20 | type Return interface{} 21 | -------------------------------------------------------------------------------- /mockgen/internal/tests/import_embedded_interface/faux/conflict.go: -------------------------------------------------------------------------------- 1 | // Copyright 2020 Google Inc. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | package faux 15 | 16 | import "github.com/golang/mock/mockgen/internal/tests/import_embedded_interface/other/log" 17 | 18 | func Conflict1() { 19 | log.Foo() 20 | } 21 | -------------------------------------------------------------------------------- /mockgen/internal/tests/import_embedded_interface/faux/faux.go: -------------------------------------------------------------------------------- 1 | // Copyright 2020 Google Inc. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | package faux 15 | 16 | import ( 17 | "log" 18 | 19 | "github.com/golang/mock/mockgen/internal/tests/import_embedded_interface/other/ersatz" 20 | ) 21 | 22 | type Foreign interface { 23 | ersatz.Embedded 24 | } 25 | 26 | func Conflict0() { 27 | log.Println() 28 | } 29 | -------------------------------------------------------------------------------- /mockgen/internal/tests/import_embedded_interface/foo.go: -------------------------------------------------------------------------------- 1 | package bugreport 2 | 3 | type Foo interface { 4 | Bar() Baz 5 | } 6 | type Baz interface{} 7 | -------------------------------------------------------------------------------- /mockgen/internal/tests/import_embedded_interface/net.go: -------------------------------------------------------------------------------- 1 | // 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | package bugreport 15 | 16 | //go:generate mockgen -destination net_mock.go -package bugreport -source=net.go 17 | 18 | import "net/http" 19 | 20 | type Net interface { 21 | http.ResponseWriter 22 | } 23 | 24 | func CallResponseWriterMethods(n Net) { 25 | n.WriteHeader(10) 26 | } 27 | -------------------------------------------------------------------------------- /mockgen/internal/tests/import_embedded_interface/net_mock.go: -------------------------------------------------------------------------------- 1 | // Code generated by MockGen. DO NOT EDIT. 2 | // Source: net.go 3 | 4 | // Package bugreport is a generated GoMock package. 5 | package bugreport 6 | 7 | import ( 8 | http "net/http" 9 | reflect "reflect" 10 | 11 | gomock "github.com/golang/mock/gomock" 12 | ) 13 | 14 | // MockNet is a mock of Net interface. 15 | type MockNet struct { 16 | ctrl *gomock.Controller 17 | recorder *MockNetMockRecorder 18 | } 19 | 20 | // MockNetMockRecorder is the mock recorder for MockNet. 21 | type MockNetMockRecorder struct { 22 | mock *MockNet 23 | } 24 | 25 | // NewMockNet creates a new mock instance. 26 | func NewMockNet(ctrl *gomock.Controller) *MockNet { 27 | mock := &MockNet{ctrl: ctrl} 28 | mock.recorder = &MockNetMockRecorder{mock} 29 | return mock 30 | } 31 | 32 | // EXPECT returns an object that allows the caller to indicate expected use. 33 | func (m *MockNet) EXPECT() *MockNetMockRecorder { 34 | return m.recorder 35 | } 36 | 37 | // Header mocks base method. 38 | func (m *MockNet) Header() http.Header { 39 | m.ctrl.T.Helper() 40 | ret := m.ctrl.Call(m, "Header") 41 | ret0, _ := ret[0].(http.Header) 42 | return ret0 43 | } 44 | 45 | // Header indicates an expected call of Header. 46 | func (mr *MockNetMockRecorder) Header() *gomock.Call { 47 | mr.mock.ctrl.T.Helper() 48 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Header", reflect.TypeOf((*MockNet)(nil).Header)) 49 | } 50 | 51 | // Write mocks base method. 52 | func (m *MockNet) Write(arg0 []byte) (int, error) { 53 | m.ctrl.T.Helper() 54 | ret := m.ctrl.Call(m, "Write", arg0) 55 | ret0, _ := ret[0].(int) 56 | ret1, _ := ret[1].(error) 57 | return ret0, ret1 58 | } 59 | 60 | // Write indicates an expected call of Write. 61 | func (mr *MockNetMockRecorder) Write(arg0 interface{}) *gomock.Call { 62 | mr.mock.ctrl.T.Helper() 63 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Write", reflect.TypeOf((*MockNet)(nil).Write), arg0) 64 | } 65 | 66 | // WriteHeader mocks base method. 67 | func (m *MockNet) WriteHeader(statusCode int) { 68 | m.ctrl.T.Helper() 69 | m.ctrl.Call(m, "WriteHeader", statusCode) 70 | } 71 | 72 | // WriteHeader indicates an expected call of WriteHeader. 73 | func (mr *MockNetMockRecorder) WriteHeader(statusCode interface{}) *gomock.Call { 74 | mr.mock.ctrl.T.Helper() 75 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "WriteHeader", reflect.TypeOf((*MockNet)(nil).WriteHeader), statusCode) 76 | } 77 | -------------------------------------------------------------------------------- /mockgen/internal/tests/import_embedded_interface/net_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2020 Google Inc. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | package bugreport 15 | 16 | import ( 17 | "testing" 18 | 19 | "github.com/golang/mock/gomock" 20 | ) 21 | 22 | // TestValidInterface assesses whether or not the generated mock is valid 23 | func TestValidNetInterface(t *testing.T) { 24 | ctrl := gomock.NewController(t) 25 | defer ctrl.Finish() 26 | 27 | s := NewMockNet(ctrl) 28 | s.EXPECT().WriteHeader(10) 29 | CallResponseWriterMethods(s) 30 | } 31 | -------------------------------------------------------------------------------- /mockgen/internal/tests/import_embedded_interface/other/ersatz/ersatz.go: -------------------------------------------------------------------------------- 1 | // Copyright 2020 Google Inc. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | package ersatz 15 | 16 | type Embedded interface { 17 | OtherErsatz() Return 18 | } 19 | 20 | type Return interface{} 21 | -------------------------------------------------------------------------------- /mockgen/internal/tests/import_embedded_interface/other/log/log.go: -------------------------------------------------------------------------------- 1 | // Copyright 2020 Google Inc. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | package log 15 | 16 | func Foo() {} 17 | -------------------------------------------------------------------------------- /mockgen/internal/tests/import_source/README.md: -------------------------------------------------------------------------------- 1 | # Import Source 2 | 3 | Test the case where the generated code uses a type defined in the source package (in source mode). There are two test cases: 4 | 5 | - the output is in a new package 6 | - the output is in the same package as the input 7 | -------------------------------------------------------------------------------- /mockgen/internal/tests/import_source/definition/source.go: -------------------------------------------------------------------------------- 1 | package source 2 | 3 | //go:generate mockgen -destination ../source_mock.go -source=source.go 4 | //go:generate mockgen -package source -destination source_mock.go -source=source.go 5 | 6 | type X struct{} 7 | 8 | type S interface { 9 | F(X) 10 | } 11 | -------------------------------------------------------------------------------- /mockgen/internal/tests/import_source/definition/source_mock.go: -------------------------------------------------------------------------------- 1 | // Code generated by MockGen. DO NOT EDIT. 2 | // Source: source.go 3 | 4 | // Package source is a generated GoMock package. 5 | package source 6 | 7 | import ( 8 | reflect "reflect" 9 | 10 | gomock "github.com/golang/mock/gomock" 11 | ) 12 | 13 | // MockS is a mock of S interface. 14 | type MockS struct { 15 | ctrl *gomock.Controller 16 | recorder *MockSMockRecorder 17 | } 18 | 19 | // MockSMockRecorder is the mock recorder for MockS. 20 | type MockSMockRecorder struct { 21 | mock *MockS 22 | } 23 | 24 | // NewMockS creates a new mock instance. 25 | func NewMockS(ctrl *gomock.Controller) *MockS { 26 | mock := &MockS{ctrl: ctrl} 27 | mock.recorder = &MockSMockRecorder{mock} 28 | return mock 29 | } 30 | 31 | // EXPECT returns an object that allows the caller to indicate expected use. 32 | func (m *MockS) EXPECT() *MockSMockRecorder { 33 | return m.recorder 34 | } 35 | 36 | // F mocks base method. 37 | func (m *MockS) F(arg0 X) { 38 | m.ctrl.T.Helper() 39 | m.ctrl.Call(m, "F", arg0) 40 | } 41 | 42 | // F indicates an expected call of F. 43 | func (mr *MockSMockRecorder) F(arg0 interface{}) *gomock.Call { 44 | mr.mock.ctrl.T.Helper() 45 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "F", reflect.TypeOf((*MockS)(nil).F), arg0) 46 | } 47 | -------------------------------------------------------------------------------- /mockgen/internal/tests/import_source/source_mock.go: -------------------------------------------------------------------------------- 1 | // Code generated by MockGen. DO NOT EDIT. 2 | // Source: source.go 3 | 4 | // Package mock_source is a generated GoMock package. 5 | package mock_source 6 | 7 | import ( 8 | reflect "reflect" 9 | 10 | gomock "github.com/golang/mock/gomock" 11 | source "github.com/golang/mock/mockgen/internal/tests/import_source/definition" 12 | ) 13 | 14 | // MockS is a mock of S interface. 15 | type MockS struct { 16 | ctrl *gomock.Controller 17 | recorder *MockSMockRecorder 18 | } 19 | 20 | // MockSMockRecorder is the mock recorder for MockS. 21 | type MockSMockRecorder struct { 22 | mock *MockS 23 | } 24 | 25 | // NewMockS creates a new mock instance. 26 | func NewMockS(ctrl *gomock.Controller) *MockS { 27 | mock := &MockS{ctrl: ctrl} 28 | mock.recorder = &MockSMockRecorder{mock} 29 | return mock 30 | } 31 | 32 | // EXPECT returns an object that allows the caller to indicate expected use. 33 | func (m *MockS) EXPECT() *MockSMockRecorder { 34 | return m.recorder 35 | } 36 | 37 | // F mocks base method. 38 | func (m *MockS) F(arg0 source.X) { 39 | m.ctrl.T.Helper() 40 | m.ctrl.Call(m, "F", arg0) 41 | } 42 | 43 | // F indicates an expected call of F. 44 | func (mr *MockSMockRecorder) F(arg0 interface{}) *gomock.Call { 45 | mr.mock.ctrl.T.Helper() 46 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "F", reflect.TypeOf((*MockS)(nil).F), arg0) 47 | } 48 | -------------------------------------------------------------------------------- /mockgen/internal/tests/internal_pkg/generate.go: -------------------------------------------------------------------------------- 1 | package test 2 | 3 | //go:generate mockgen -destination subdir/internal/pkg/reflect_output/mock.go github.com/golang/mock/mockgen/internal/tests/internal_pkg/subdir/internal/pkg Intf 4 | //go:generate mockgen -source subdir/internal/pkg/input.go -destination subdir/internal/pkg/source_output/mock.go 5 | -------------------------------------------------------------------------------- /mockgen/internal/tests/internal_pkg/subdir/internal/pkg/input.go: -------------------------------------------------------------------------------- 1 | package pkg 2 | 3 | type Arg interface { 4 | Foo() int 5 | } 6 | 7 | type Intf interface { 8 | F() Arg 9 | } 10 | -------------------------------------------------------------------------------- /mockgen/internal/tests/internal_pkg/subdir/internal/pkg/reflect_output/mock.go: -------------------------------------------------------------------------------- 1 | // Code generated by MockGen. DO NOT EDIT. 2 | // Source: github.com/golang/mock/mockgen/internal/tests/internal_pkg/subdir/internal/pkg (interfaces: Intf) 3 | 4 | // Package mock_pkg is a generated GoMock package. 5 | package mock_pkg 6 | 7 | import ( 8 | reflect "reflect" 9 | 10 | gomock "github.com/golang/mock/gomock" 11 | pkg "github.com/golang/mock/mockgen/internal/tests/internal_pkg/subdir/internal/pkg" 12 | ) 13 | 14 | // MockIntf is a mock of Intf interface. 15 | type MockIntf struct { 16 | ctrl *gomock.Controller 17 | recorder *MockIntfMockRecorder 18 | } 19 | 20 | // MockIntfMockRecorder is the mock recorder for MockIntf. 21 | type MockIntfMockRecorder struct { 22 | mock *MockIntf 23 | } 24 | 25 | // NewMockIntf creates a new mock instance. 26 | func NewMockIntf(ctrl *gomock.Controller) *MockIntf { 27 | mock := &MockIntf{ctrl: ctrl} 28 | mock.recorder = &MockIntfMockRecorder{mock} 29 | return mock 30 | } 31 | 32 | // EXPECT returns an object that allows the caller to indicate expected use. 33 | func (m *MockIntf) EXPECT() *MockIntfMockRecorder { 34 | return m.recorder 35 | } 36 | 37 | // F mocks base method. 38 | func (m *MockIntf) F() pkg.Arg { 39 | m.ctrl.T.Helper() 40 | ret := m.ctrl.Call(m, "F") 41 | ret0, _ := ret[0].(pkg.Arg) 42 | return ret0 43 | } 44 | 45 | // F indicates an expected call of F. 46 | func (mr *MockIntfMockRecorder) F() *gomock.Call { 47 | mr.mock.ctrl.T.Helper() 48 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "F", reflect.TypeOf((*MockIntf)(nil).F)) 49 | } 50 | -------------------------------------------------------------------------------- /mockgen/internal/tests/internal_pkg/subdir/internal/pkg/source_output/mock.go: -------------------------------------------------------------------------------- 1 | // Code generated by MockGen. DO NOT EDIT. 2 | // Source: subdir/internal/pkg/input.go 3 | 4 | // Package mock_pkg is a generated GoMock package. 5 | package mock_pkg 6 | 7 | import ( 8 | reflect "reflect" 9 | 10 | gomock "github.com/golang/mock/gomock" 11 | pkg "github.com/golang/mock/mockgen/internal/tests/internal_pkg/subdir/internal/pkg" 12 | ) 13 | 14 | // MockArg is a mock of Arg interface. 15 | type MockArg struct { 16 | ctrl *gomock.Controller 17 | recorder *MockArgMockRecorder 18 | } 19 | 20 | // MockArgMockRecorder is the mock recorder for MockArg. 21 | type MockArgMockRecorder struct { 22 | mock *MockArg 23 | } 24 | 25 | // NewMockArg creates a new mock instance. 26 | func NewMockArg(ctrl *gomock.Controller) *MockArg { 27 | mock := &MockArg{ctrl: ctrl} 28 | mock.recorder = &MockArgMockRecorder{mock} 29 | return mock 30 | } 31 | 32 | // EXPECT returns an object that allows the caller to indicate expected use. 33 | func (m *MockArg) EXPECT() *MockArgMockRecorder { 34 | return m.recorder 35 | } 36 | 37 | // Foo mocks base method. 38 | func (m *MockArg) Foo() int { 39 | m.ctrl.T.Helper() 40 | ret := m.ctrl.Call(m, "Foo") 41 | ret0, _ := ret[0].(int) 42 | return ret0 43 | } 44 | 45 | // Foo indicates an expected call of Foo. 46 | func (mr *MockArgMockRecorder) Foo() *gomock.Call { 47 | mr.mock.ctrl.T.Helper() 48 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Foo", reflect.TypeOf((*MockArg)(nil).Foo)) 49 | } 50 | 51 | // MockIntf is a mock of Intf interface. 52 | type MockIntf struct { 53 | ctrl *gomock.Controller 54 | recorder *MockIntfMockRecorder 55 | } 56 | 57 | // MockIntfMockRecorder is the mock recorder for MockIntf. 58 | type MockIntfMockRecorder struct { 59 | mock *MockIntf 60 | } 61 | 62 | // NewMockIntf creates a new mock instance. 63 | func NewMockIntf(ctrl *gomock.Controller) *MockIntf { 64 | mock := &MockIntf{ctrl: ctrl} 65 | mock.recorder = &MockIntfMockRecorder{mock} 66 | return mock 67 | } 68 | 69 | // EXPECT returns an object that allows the caller to indicate expected use. 70 | func (m *MockIntf) EXPECT() *MockIntfMockRecorder { 71 | return m.recorder 72 | } 73 | 74 | // F mocks base method. 75 | func (m *MockIntf) F() pkg.Arg { 76 | m.ctrl.T.Helper() 77 | ret := m.ctrl.Call(m, "F") 78 | ret0, _ := ret[0].(pkg.Arg) 79 | return ret0 80 | } 81 | 82 | // F indicates an expected call of F. 83 | func (mr *MockIntfMockRecorder) F() *gomock.Call { 84 | mr.mock.ctrl.T.Helper() 85 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "F", reflect.TypeOf((*MockIntf)(nil).F)) 86 | } 87 | -------------------------------------------------------------------------------- /mockgen/internal/tests/missing_import/output/source_mock.go: -------------------------------------------------------------------------------- 1 | // Code generated by MockGen. DO NOT EDIT. 2 | // Source: source.go 3 | 4 | // Package source is a generated GoMock package. 5 | package source 6 | 7 | import ( 8 | reflect "reflect" 9 | 10 | gomock "github.com/golang/mock/gomock" 11 | source "github.com/golang/mock/mockgen/internal/tests/missing_import/source" 12 | ) 13 | 14 | // MockBar is a mock of Bar interface. 15 | type MockBar struct { 16 | ctrl *gomock.Controller 17 | recorder *MockBarMockRecorder 18 | } 19 | 20 | // MockBarMockRecorder is the mock recorder for MockBar. 21 | type MockBarMockRecorder struct { 22 | mock *MockBar 23 | } 24 | 25 | // NewMockBar creates a new mock instance. 26 | func NewMockBar(ctrl *gomock.Controller) *MockBar { 27 | mock := &MockBar{ctrl: ctrl} 28 | mock.recorder = &MockBarMockRecorder{mock} 29 | return mock 30 | } 31 | 32 | // EXPECT returns an object that allows the caller to indicate expected use. 33 | func (m *MockBar) EXPECT() *MockBarMockRecorder { 34 | return m.recorder 35 | } 36 | 37 | // Baz mocks base method. 38 | func (m *MockBar) Baz(arg0 source.Foo) { 39 | m.ctrl.T.Helper() 40 | m.ctrl.Call(m, "Baz", arg0) 41 | } 42 | 43 | // Baz indicates an expected call of Baz. 44 | func (mr *MockBarMockRecorder) Baz(arg0 interface{}) *gomock.Call { 45 | mr.mock.ctrl.T.Helper() 46 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Baz", reflect.TypeOf((*MockBar)(nil).Baz), arg0) 47 | } 48 | -------------------------------------------------------------------------------- /mockgen/internal/tests/missing_import/source/source.go: -------------------------------------------------------------------------------- 1 | // Package source makes sure output imports its. See #505. 2 | package source 3 | 4 | //go:generate mockgen -package source -destination=../output/source_mock.go -source=source.go 5 | 6 | type Foo struct{} 7 | 8 | type Bar interface { 9 | Baz(Foo) 10 | } 11 | -------------------------------------------------------------------------------- /mockgen/internal/tests/mock_in_test_package/README.md: -------------------------------------------------------------------------------- 1 | # Mock in Test Package 2 | 3 | Test the case where the package has the `_test` suffix. 4 | 5 | Prior to patch: 6 | 7 | ```bash 8 | $ go generate 9 | $ go test 10 | # github.com/golang/mock/mockgen/internal/tests/mock_in_test_package_test [github.com/golang/mock/mockgen/internal/tests/mock_in_test_package.test] 11 | ./mock_test.go:36:44: undefined: User 12 | ./mock_test.go:38:21: undefined: User 13 | FAIL github.com/golang/mock/mockgen/internal/tests/mock_in_test_package [build failed] 14 | ``` 15 | 16 | With this patch applied: 17 | 18 | ```bash 19 | $ go generate 20 | $ go test 21 | ok github.com/golang/mock/mockgen/internal/tests/mock_in_test_package 0.031s 22 | ``` 23 | -------------------------------------------------------------------------------- /mockgen/internal/tests/mock_in_test_package/mock_test.go: -------------------------------------------------------------------------------- 1 | // Code generated by MockGen. DO NOT EDIT. 2 | // Source: user.go 3 | 4 | // Package users_test is a generated GoMock package. 5 | package users_test 6 | 7 | import ( 8 | reflect "reflect" 9 | 10 | gomock "github.com/golang/mock/gomock" 11 | users "github.com/golang/mock/mockgen/internal/tests/mock_in_test_package" 12 | ) 13 | 14 | // MockFinder is a mock of Finder interface. 15 | type MockFinder struct { 16 | ctrl *gomock.Controller 17 | recorder *MockFinderMockRecorder 18 | } 19 | 20 | // MockFinderMockRecorder is the mock recorder for MockFinder. 21 | type MockFinderMockRecorder struct { 22 | mock *MockFinder 23 | } 24 | 25 | // NewMockFinder creates a new mock instance. 26 | func NewMockFinder(ctrl *gomock.Controller) *MockFinder { 27 | mock := &MockFinder{ctrl: ctrl} 28 | mock.recorder = &MockFinderMockRecorder{mock} 29 | return mock 30 | } 31 | 32 | // EXPECT returns an object that allows the caller to indicate expected use. 33 | func (m *MockFinder) EXPECT() *MockFinderMockRecorder { 34 | return m.recorder 35 | } 36 | 37 | // Add mocks base method. 38 | func (m *MockFinder) Add(u users.User) { 39 | m.ctrl.T.Helper() 40 | m.ctrl.Call(m, "Add", u) 41 | } 42 | 43 | // Add indicates an expected call of Add. 44 | func (mr *MockFinderMockRecorder) Add(u interface{}) *gomock.Call { 45 | mr.mock.ctrl.T.Helper() 46 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Add", reflect.TypeOf((*MockFinder)(nil).Add), u) 47 | } 48 | 49 | // FindUser mocks base method. 50 | func (m *MockFinder) FindUser(name string) users.User { 51 | m.ctrl.T.Helper() 52 | ret := m.ctrl.Call(m, "FindUser", name) 53 | ret0, _ := ret[0].(users.User) 54 | return ret0 55 | } 56 | 57 | // FindUser indicates an expected call of FindUser. 58 | func (mr *MockFinderMockRecorder) FindUser(name interface{}) *gomock.Call { 59 | mr.mock.ctrl.T.Helper() 60 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FindUser", reflect.TypeOf((*MockFinder)(nil).FindUser), name) 61 | } 62 | -------------------------------------------------------------------------------- /mockgen/internal/tests/mock_in_test_package/user.go: -------------------------------------------------------------------------------- 1 | package users 2 | 3 | //go:generate mockgen --source=user.go --destination=mock_test.go --package=users_test 4 | 5 | type User struct { 6 | Name string 7 | } 8 | 9 | type Finder interface { 10 | FindUser(name string) User 11 | Add(u User) 12 | } 13 | -------------------------------------------------------------------------------- /mockgen/internal/tests/overlapping_methods/interfaces.go: -------------------------------------------------------------------------------- 1 | package overlap 2 | 3 | type ReadCloser interface { 4 | Read([]byte) (int, error) 5 | Close() error 6 | } 7 | 8 | type WriteCloser interface { 9 | Write([]byte) (int, error) 10 | Close() error 11 | } 12 | -------------------------------------------------------------------------------- /mockgen/internal/tests/overlapping_methods/mock.go: -------------------------------------------------------------------------------- 1 | // Code generated by MockGen. DO NOT EDIT. 2 | // Source: overlap.go 3 | 4 | // Package overlap is a generated GoMock package. 5 | package overlap 6 | 7 | import ( 8 | reflect "reflect" 9 | 10 | gomock "github.com/golang/mock/gomock" 11 | ) 12 | 13 | // MockReadWriteCloser is a mock of ReadWriteCloser interface. 14 | type MockReadWriteCloser struct { 15 | ctrl *gomock.Controller 16 | recorder *MockReadWriteCloserMockRecorder 17 | } 18 | 19 | // MockReadWriteCloserMockRecorder is the mock recorder for MockReadWriteCloser. 20 | type MockReadWriteCloserMockRecorder struct { 21 | mock *MockReadWriteCloser 22 | } 23 | 24 | // NewMockReadWriteCloser creates a new mock instance. 25 | func NewMockReadWriteCloser(ctrl *gomock.Controller) *MockReadWriteCloser { 26 | mock := &MockReadWriteCloser{ctrl: ctrl} 27 | mock.recorder = &MockReadWriteCloserMockRecorder{mock} 28 | return mock 29 | } 30 | 31 | // EXPECT returns an object that allows the caller to indicate expected use. 32 | func (m *MockReadWriteCloser) EXPECT() *MockReadWriteCloserMockRecorder { 33 | return m.recorder 34 | } 35 | 36 | // Close mocks base method. 37 | func (m *MockReadWriteCloser) Close() error { 38 | m.ctrl.T.Helper() 39 | ret := m.ctrl.Call(m, "Close") 40 | ret0, _ := ret[0].(error) 41 | return ret0 42 | } 43 | 44 | // Close indicates an expected call of Close. 45 | func (mr *MockReadWriteCloserMockRecorder) Close() *gomock.Call { 46 | mr.mock.ctrl.T.Helper() 47 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Close", reflect.TypeOf((*MockReadWriteCloser)(nil).Close)) 48 | } 49 | 50 | // Read mocks base method. 51 | func (m *MockReadWriteCloser) Read(arg0 []byte) (int, error) { 52 | m.ctrl.T.Helper() 53 | ret := m.ctrl.Call(m, "Read", arg0) 54 | ret0, _ := ret[0].(int) 55 | ret1, _ := ret[1].(error) 56 | return ret0, ret1 57 | } 58 | 59 | // Read indicates an expected call of Read. 60 | func (mr *MockReadWriteCloserMockRecorder) Read(arg0 interface{}) *gomock.Call { 61 | mr.mock.ctrl.T.Helper() 62 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Read", reflect.TypeOf((*MockReadWriteCloser)(nil).Read), arg0) 63 | } 64 | 65 | // Write mocks base method. 66 | func (m *MockReadWriteCloser) Write(arg0 []byte) (int, error) { 67 | m.ctrl.T.Helper() 68 | ret := m.ctrl.Call(m, "Write", arg0) 69 | ret0, _ := ret[0].(int) 70 | ret1, _ := ret[1].(error) 71 | return ret0, ret1 72 | } 73 | 74 | // Write indicates an expected call of Write. 75 | func (mr *MockReadWriteCloserMockRecorder) Write(arg0 interface{}) *gomock.Call { 76 | mr.mock.ctrl.T.Helper() 77 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Write", reflect.TypeOf((*MockReadWriteCloser)(nil).Write), arg0) 78 | } 79 | -------------------------------------------------------------------------------- /mockgen/internal/tests/overlapping_methods/overlap.go: -------------------------------------------------------------------------------- 1 | package overlap 2 | 3 | //go:generate mockgen -package overlap -destination mock.go -source overlap.go -aux_files github.com/golang/mock/mockgen/internal/tests/overlapping_methods=interfaces.go 4 | 5 | type ReadWriteCloser interface { 6 | ReadCloser 7 | WriteCloser 8 | } 9 | -------------------------------------------------------------------------------- /mockgen/internal/tests/overlapping_methods/overlap_test.go: -------------------------------------------------------------------------------- 1 | package overlap 2 | 3 | import ( 4 | "errors" 5 | "testing" 6 | 7 | gomock "github.com/golang/mock/gomock" 8 | ) 9 | 10 | // TestValidInterface assesses whether or not the generated mock is valid 11 | func TestValidInterface(t *testing.T) { 12 | ctrl := gomock.NewController(t) 13 | defer ctrl.Finish() 14 | 15 | s := NewMockReadWriteCloser(ctrl) 16 | s.EXPECT().Close().Return(errors.New("test")) 17 | 18 | s.Close() 19 | } 20 | -------------------------------------------------------------------------------- /mockgen/internal/tests/panicing_test/mock_test.go: -------------------------------------------------------------------------------- 1 | // Code generated by MockGen. DO NOT EDIT. 2 | // Source: panic.go 3 | 4 | // Package paniccode is a generated GoMock package. 5 | package paniccode 6 | 7 | import ( 8 | reflect "reflect" 9 | 10 | gomock "github.com/golang/mock/gomock" 11 | ) 12 | 13 | // MockFoo is a mock of Foo interface. 14 | type MockFoo struct { 15 | ctrl *gomock.Controller 16 | recorder *MockFooMockRecorder 17 | } 18 | 19 | // MockFooMockRecorder is the mock recorder for MockFoo. 20 | type MockFooMockRecorder struct { 21 | mock *MockFoo 22 | } 23 | 24 | // NewMockFoo creates a new mock instance. 25 | func NewMockFoo(ctrl *gomock.Controller) *MockFoo { 26 | mock := &MockFoo{ctrl: ctrl} 27 | mock.recorder = &MockFooMockRecorder{mock} 28 | return mock 29 | } 30 | 31 | // EXPECT returns an object that allows the caller to indicate expected use. 32 | func (m *MockFoo) EXPECT() *MockFooMockRecorder { 33 | return m.recorder 34 | } 35 | 36 | // Bar mocks base method. 37 | func (m *MockFoo) Bar() string { 38 | m.ctrl.T.Helper() 39 | ret := m.ctrl.Call(m, "Bar") 40 | ret0, _ := ret[0].(string) 41 | return ret0 42 | } 43 | 44 | // Bar indicates an expected call of Bar. 45 | func (mr *MockFooMockRecorder) Bar() *gomock.Call { 46 | mr.mock.ctrl.T.Helper() 47 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Bar", reflect.TypeOf((*MockFoo)(nil).Bar)) 48 | } 49 | 50 | // Baz mocks base method. 51 | func (m *MockFoo) Baz() string { 52 | m.ctrl.T.Helper() 53 | ret := m.ctrl.Call(m, "Baz") 54 | ret0, _ := ret[0].(string) 55 | return ret0 56 | } 57 | 58 | // Baz indicates an expected call of Baz. 59 | func (mr *MockFooMockRecorder) Baz() *gomock.Call { 60 | mr.mock.ctrl.T.Helper() 61 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Baz", reflect.TypeOf((*MockFoo)(nil).Baz)) 62 | } 63 | -------------------------------------------------------------------------------- /mockgen/internal/tests/panicing_test/panic.go: -------------------------------------------------------------------------------- 1 | // Copyright 2020 Google LLC 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package paniccode 16 | 17 | //go:generate mockgen --source=panic.go --destination=mock_test.go --package=paniccode 18 | 19 | type Foo interface { 20 | Bar() string 21 | Baz() string 22 | } 23 | 24 | func Danger(f Foo) { 25 | if f.Bar() == "Bar" { 26 | panic("Danger, Will Robinson!") 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /mockgen/internal/tests/panicing_test/panic_test.go: -------------------------------------------------------------------------------- 1 | //go:build panictest 2 | // +build panictest 3 | 4 | // Copyright 2020 Google LLC 5 | // 6 | // Licensed under the Apache License, Version 2.0 (the "License"); 7 | // you may not use this file except in compliance with the License. 8 | // You may obtain a copy of the License at 9 | // 10 | // http://www.apache.org/licenses/LICENSE-2.0 11 | // 12 | // Unless required by applicable law or agreed to in writing, software 13 | // distributed under the License is distributed on an "AS IS" BASIS, 14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | // See the License for the specific language governing permissions and 16 | // limitations under the License. 17 | 18 | package paniccode 19 | 20 | import ( 21 | "testing" 22 | 23 | "github.com/golang/mock/gomock" 24 | ) 25 | 26 | func TestDanger_Panics_Explicit(t *testing.T) { 27 | ctrl := gomock.NewController(t) 28 | defer ctrl.Finish() 29 | mock := NewMockFoo(ctrl) 30 | mock.EXPECT().Bar().Return("Bar") 31 | mock.EXPECT().Bar().Return("Baz") 32 | Danger(mock) 33 | } 34 | 35 | func TestDanger_Panics_Implicit(t *testing.T) { 36 | ctrl := gomock.NewController(t) 37 | mock := NewMockFoo(ctrl) 38 | mock.EXPECT().Bar().Return("Bar") 39 | mock.EXPECT().Bar().Return("Baz") 40 | Danger(mock) 41 | } 42 | -------------------------------------------------------------------------------- /mockgen/internal/tests/parenthesized_parameter_type/README.md: -------------------------------------------------------------------------------- 1 | # Parenthesized Parameter Type 2 | 3 | Test for [Issue#416](https://github.com/golang/mock/issues/416). 4 | -------------------------------------------------------------------------------- /mockgen/internal/tests/parenthesized_parameter_type/input.go: -------------------------------------------------------------------------------- 1 | package parenthesized_parameter_type 2 | 3 | type Example interface { 4 | ParenthesizedParameterType(param *(int)) 5 | } 6 | -------------------------------------------------------------------------------- /mockgen/internal/tests/parenthesized_parameter_type/mock.go: -------------------------------------------------------------------------------- 1 | // Code generated by MockGen. DO NOT EDIT. 2 | // Source: ./mockgen/internal/tests/parenthesized_parameter_type/input.go 3 | 4 | // Package parenthesized_parameter_type is a generated GoMock package. 5 | package parenthesized_parameter_type 6 | 7 | import ( 8 | gomock "github.com/golang/mock/gomock" 9 | reflect "reflect" 10 | ) 11 | 12 | // MockExample is a mock of Example interface. 13 | type MockExample struct { 14 | ctrl *gomock.Controller 15 | recorder *MockExampleMockRecorder 16 | } 17 | 18 | // MockExampleMockRecorder is the mock recorder for MockExample. 19 | type MockExampleMockRecorder struct { 20 | mock *MockExample 21 | } 22 | 23 | // NewMockExample creates a new mock instance. 24 | func NewMockExample(ctrl *gomock.Controller) *MockExample { 25 | mock := &MockExample{ctrl: ctrl} 26 | mock.recorder = &MockExampleMockRecorder{mock} 27 | return mock 28 | } 29 | 30 | // EXPECT returns an object that allows the caller to indicate expected use. 31 | func (m *MockExample) EXPECT() *MockExampleMockRecorder { 32 | return m.recorder 33 | } 34 | 35 | // ParenthesizedParameterType mocks base method. 36 | func (m *MockExample) ParenthesizedParameterType(param *int) { 37 | m.ctrl.T.Helper() 38 | m.ctrl.Call(m, "ParenthesizedParameterType", param) 39 | } 40 | 41 | // ParenthesizedParameterType indicates an expected call of ParenthesizedParameterType. 42 | func (mr *MockExampleMockRecorder) ParenthesizedParameterType(param interface{}) *gomock.Call { 43 | mr.mock.ctrl.T.Helper() 44 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ParenthesizedParameterType", reflect.TypeOf((*MockExample)(nil).ParenthesizedParameterType), param) 45 | } 46 | -------------------------------------------------------------------------------- /mockgen/internal/tests/performance/big_interface/big_interface.go: -------------------------------------------------------------------------------- 1 | package big_interface 2 | 3 | type Bar struct{} 4 | 5 | type BigInterface interface { 6 | Foo1(bool, bool, bool, bool, bool, bool, bool, bool) Bar 7 | Foo2(bool, bool, bool, bool, bool, bool, bool, bool) Bar 8 | Foo3(bool, bool, bool, bool, bool, bool, bool, bool) Bar 9 | Foo4(bool, bool, bool, bool, bool, bool, bool, bool) Bar 10 | Foo5(bool, bool, bool, bool, bool, bool, bool, bool) Bar 11 | Foo6(bool, bool, bool, bool, bool, bool, bool, bool) Bar 12 | Foo7(bool, bool, bool, bool, bool, bool, bool, bool) Bar 13 | Foo8(bool, bool, bool, bool, bool, bool, bool, bool) Bar 14 | Foo9(bool, bool, bool, bool, bool, bool, bool, bool) Bar 15 | Foo10(bool, bool, bool, bool, bool, bool, bool, bool) Bar 16 | Foo11(bool, bool, bool, bool, bool, bool, bool, bool) Bar 17 | Foo12(bool, bool, bool, bool, bool, bool, bool, bool) Bar 18 | Foo13(bool, bool, bool, bool, bool, bool, bool, bool) Bar 19 | Foo14(bool, bool, bool, bool, bool, bool, bool, bool) Bar 20 | Foo15(bool, bool, bool, bool, bool, bool, bool, bool) Bar 21 | Foo16(bool, bool, bool, bool, bool, bool, bool, bool) Bar 22 | Foo17(bool, bool, bool, bool, bool, bool, bool, bool) Bar 23 | Foo18(bool, bool, bool, bool, bool, bool, bool, bool) Bar 24 | Foo19(bool, bool, bool, bool, bool, bool, bool, bool) Bar 25 | Foo20(bool, bool, bool, bool, bool, bool, bool, bool) Bar 26 | Foo21(bool, bool, bool, bool, bool, bool, bool, bool) Bar 27 | Foo22(bool, bool, bool, bool, bool, bool, bool, bool) Bar 28 | Foo23(bool, bool, bool, bool, bool, bool, bool, bool) Bar 29 | Foo24(bool, bool, bool, bool, bool, bool, bool, bool) Bar 30 | Foo25(bool, bool, bool, bool, bool, bool, bool, bool) Bar 31 | Foo26(bool, bool, bool, bool, bool, bool, bool, bool) Bar 32 | Foo27(bool, bool, bool, bool, bool, bool, bool, bool) Bar 33 | Foo28(bool, bool, bool, bool, bool, bool, bool, bool) Bar 34 | Foo29(bool, bool, bool, bool, bool, bool, bool, bool) Bar 35 | Foo30(bool, bool, bool, bool, bool, bool, bool, bool) Bar 36 | Foo31(bool, bool, bool, bool, bool, bool, bool, bool) Bar 37 | Foo32(bool, bool, bool, bool, bool, bool, bool, bool) Bar 38 | Foo33(bool, bool, bool, bool, bool, bool, bool, bool) Bar 39 | Foo34(bool, bool, bool, bool, bool, bool, bool, bool) Bar 40 | Foo35(bool, bool, bool, bool, bool, bool, bool, bool) Bar 41 | Foo36(bool, bool, bool, bool, bool, bool, bool, bool) Bar 42 | Foo37(bool, bool, bool, bool, bool, bool, bool, bool) Bar 43 | Foo38(bool, bool, bool, bool, bool, bool, bool, bool) Bar 44 | Foo39(bool, bool, bool, bool, bool, bool, bool, bool) Bar 45 | Foo40(bool, bool, bool, bool, bool, bool, bool, bool) Bar 46 | Foo41(bool, bool, bool, bool, bool, bool, bool, bool) Bar 47 | Foo42(bool, bool, bool, bool, bool, bool, bool, bool) Bar 48 | Foo43(bool, bool, bool, bool, bool, bool, bool, bool) Bar 49 | Foo44(bool, bool, bool, bool, bool, bool, bool, bool) Bar 50 | Foo45(bool, bool, bool, bool, bool, bool, bool, bool) Bar 51 | Foo46(bool, bool, bool, bool, bool, bool, bool, bool) Bar 52 | Foo47(bool, bool, bool, bool, bool, bool, bool, bool) Bar 53 | Foo48(bool, bool, bool, bool, bool, bool, bool, bool) Bar 54 | Foo49(bool, bool, bool, bool, bool, bool, bool, bool) Bar 55 | Foo50(bool, bool, bool, bool, bool, bool, bool, bool) Bar 56 | Foo51(bool, bool, bool, bool, bool, bool, bool, bool) Bar 57 | Foo52(bool, bool, bool, bool, bool, bool, bool, bool) Bar 58 | Foo53(bool, bool, bool, bool, bool, bool, bool, bool) Bar 59 | Foo54(bool, bool, bool, bool, bool, bool, bool, bool) Bar 60 | Foo55(bool, bool, bool, bool, bool, bool, bool, bool) Bar 61 | Foo56(bool, bool, bool, bool, bool, bool, bool, bool) Bar 62 | Foo57(bool, bool, bool, bool, bool, bool, bool, bool) Bar 63 | Foo58(bool, bool, bool, bool, bool, bool, bool, bool) Bar 64 | Foo59(bool, bool, bool, bool, bool, bool, bool, bool) Bar 65 | Foo60(bool, bool, bool, bool, bool, bool, bool, bool) Bar 66 | } 67 | -------------------------------------------------------------------------------- /mockgen/internal/tests/self_package/mock.go: -------------------------------------------------------------------------------- 1 | // Code generated by MockGen. DO NOT EDIT. 2 | // Source: github.com/golang/mock/mockgen/internal/tests/self_package (interfaces: Methods) 3 | 4 | // Package core is a generated GoMock package. 5 | package core 6 | 7 | import ( 8 | reflect "reflect" 9 | 10 | gomock "github.com/golang/mock/gomock" 11 | ) 12 | 13 | // MockMethods is a mock of Methods interface. 14 | type MockMethods struct { 15 | ctrl *gomock.Controller 16 | recorder *MockMethodsMockRecorder 17 | } 18 | 19 | // MockMethodsMockRecorder is the mock recorder for MockMethods. 20 | type MockMethodsMockRecorder struct { 21 | mock *MockMethods 22 | } 23 | 24 | // NewMockMethods creates a new mock instance. 25 | func NewMockMethods(ctrl *gomock.Controller) *MockMethods { 26 | mock := &MockMethods{ctrl: ctrl} 27 | mock.recorder = &MockMethodsMockRecorder{mock} 28 | return mock 29 | } 30 | 31 | // EXPECT returns an object that allows the caller to indicate expected use. 32 | func (m *MockMethods) EXPECT() *MockMethodsMockRecorder { 33 | return m.recorder 34 | } 35 | 36 | // getInfo mocks base method. 37 | func (m *MockMethods) getInfo() Info { 38 | m.ctrl.T.Helper() 39 | ret := m.ctrl.Call(m, "getInfo") 40 | ret0, _ := ret[0].(Info) 41 | return ret0 42 | } 43 | 44 | // getInfo indicates an expected call of getInfo. 45 | func (mr *MockMethodsMockRecorder) getInfo() *gomock.Call { 46 | mr.mock.ctrl.T.Helper() 47 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "getInfo", reflect.TypeOf((*MockMethods)(nil).getInfo)) 48 | } 49 | -------------------------------------------------------------------------------- /mockgen/internal/tests/self_package/types.go: -------------------------------------------------------------------------------- 1 | package core 2 | 3 | //go:generate mockgen -package core -self_package github.com/golang/mock/mockgen/internal/tests/self_package -destination mock.go github.com/golang/mock/mockgen/internal/tests/self_package Methods 4 | 5 | type Info struct{} 6 | 7 | type Methods interface { 8 | getInfo() Info 9 | } 10 | -------------------------------------------------------------------------------- /mockgen/internal/tests/test_package/foo.go: -------------------------------------------------------------------------------- 1 | package users 2 | -------------------------------------------------------------------------------- /mockgen/internal/tests/test_package/mock_test.go: -------------------------------------------------------------------------------- 1 | // Code generated by MockGen. DO NOT EDIT. 2 | // Source: user_test.go 3 | 4 | // Package users_test is a generated GoMock package. 5 | package users_test 6 | 7 | import ( 8 | reflect "reflect" 9 | 10 | gomock "github.com/golang/mock/gomock" 11 | ) 12 | 13 | // MockFinder is a mock of Finder interface. 14 | type MockFinder struct { 15 | ctrl *gomock.Controller 16 | recorder *MockFinderMockRecorder 17 | } 18 | 19 | // MockFinderMockRecorder is the mock recorder for MockFinder. 20 | type MockFinderMockRecorder struct { 21 | mock *MockFinder 22 | } 23 | 24 | // NewMockFinder creates a new mock instance. 25 | func NewMockFinder(ctrl *gomock.Controller) *MockFinder { 26 | mock := &MockFinder{ctrl: ctrl} 27 | mock.recorder = &MockFinderMockRecorder{mock} 28 | return mock 29 | } 30 | 31 | // EXPECT returns an object that allows the caller to indicate expected use. 32 | func (m *MockFinder) EXPECT() *MockFinderMockRecorder { 33 | return m.recorder 34 | } 35 | 36 | // Add mocks base method. 37 | func (m *MockFinder) Add(u User) { 38 | m.ctrl.T.Helper() 39 | m.ctrl.Call(m, "Add", u) 40 | } 41 | 42 | // Add indicates an expected call of Add. 43 | func (mr *MockFinderMockRecorder) Add(u interface{}) *gomock.Call { 44 | mr.mock.ctrl.T.Helper() 45 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Add", reflect.TypeOf((*MockFinder)(nil).Add), u) 46 | } 47 | 48 | // FindUser mocks base method. 49 | func (m *MockFinder) FindUser(name string) User { 50 | m.ctrl.T.Helper() 51 | ret := m.ctrl.Call(m, "FindUser", name) 52 | ret0, _ := ret[0].(User) 53 | return ret0 54 | } 55 | 56 | // FindUser indicates an expected call of FindUser. 57 | func (mr *MockFinderMockRecorder) FindUser(name interface{}) *gomock.Call { 58 | mr.mock.ctrl.T.Helper() 59 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FindUser", reflect.TypeOf((*MockFinder)(nil).FindUser), name) 60 | } 61 | -------------------------------------------------------------------------------- /mockgen/internal/tests/test_package/user_test.go: -------------------------------------------------------------------------------- 1 | package users_test 2 | 3 | //go:generate mockgen --source=user_test.go --destination=mock_test.go --package=users_test 4 | 5 | type User struct { 6 | Name string 7 | } 8 | 9 | type Finder interface { 10 | FindUser(name string) User 11 | Add(u User) 12 | } 13 | -------------------------------------------------------------------------------- /mockgen/internal/tests/unexported_method/README.md: -------------------------------------------------------------------------------- 1 | # Unexported Method 2 | 3 | From #52, this tests an unexported method in the mocked interface. 4 | -------------------------------------------------------------------------------- /mockgen/internal/tests/unexported_method/bugreport.go: -------------------------------------------------------------------------------- 1 | package bugreport 2 | 3 | //go:generate mockgen -destination bugreport_mock.go -package bugreport -source=bugreport.go Example 4 | 5 | import "fmt" 6 | 7 | // Example is an interface with a non exported method 8 | type Example interface { 9 | someMethod(string) string 10 | } 11 | 12 | // CallExample is a simple function that uses the interface 13 | func CallExample(e Example) { 14 | fmt.Println(e.someMethod("test")) 15 | } 16 | -------------------------------------------------------------------------------- /mockgen/internal/tests/unexported_method/bugreport_mock.go: -------------------------------------------------------------------------------- 1 | // Code generated by MockGen. DO NOT EDIT. 2 | // Source: bugreport.go 3 | 4 | // Package bugreport is a generated GoMock package. 5 | package bugreport 6 | 7 | import ( 8 | reflect "reflect" 9 | 10 | gomock "github.com/golang/mock/gomock" 11 | ) 12 | 13 | // MockExample is a mock of Example interface. 14 | type MockExample struct { 15 | ctrl *gomock.Controller 16 | recorder *MockExampleMockRecorder 17 | } 18 | 19 | // MockExampleMockRecorder is the mock recorder for MockExample. 20 | type MockExampleMockRecorder struct { 21 | mock *MockExample 22 | } 23 | 24 | // NewMockExample creates a new mock instance. 25 | func NewMockExample(ctrl *gomock.Controller) *MockExample { 26 | mock := &MockExample{ctrl: ctrl} 27 | mock.recorder = &MockExampleMockRecorder{mock} 28 | return mock 29 | } 30 | 31 | // EXPECT returns an object that allows the caller to indicate expected use. 32 | func (m *MockExample) EXPECT() *MockExampleMockRecorder { 33 | return m.recorder 34 | } 35 | 36 | // someMethod mocks base method. 37 | func (m *MockExample) someMethod(arg0 string) string { 38 | m.ctrl.T.Helper() 39 | ret := m.ctrl.Call(m, "someMethod", arg0) 40 | ret0, _ := ret[0].(string) 41 | return ret0 42 | } 43 | 44 | // someMethod indicates an expected call of someMethod. 45 | func (mr *MockExampleMockRecorder) someMethod(arg0 interface{}) *gomock.Call { 46 | mr.mock.ctrl.T.Helper() 47 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "someMethod", reflect.TypeOf((*MockExample)(nil).someMethod), arg0) 48 | } 49 | -------------------------------------------------------------------------------- /mockgen/internal/tests/unexported_method/bugreport_test.go: -------------------------------------------------------------------------------- 1 | package bugreport 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/golang/mock/gomock" 7 | ) 8 | 9 | func TestCallExample(t *testing.T) { 10 | ctrl := gomock.NewController(t) 11 | defer ctrl.Finish() 12 | 13 | e := NewMockExample(ctrl) 14 | e.EXPECT().someMethod(gomock.Any()).Return("it works!") 15 | 16 | CallExample(e) 17 | } 18 | -------------------------------------------------------------------------------- /mockgen/internal/tests/vendor_dep/README.md: -------------------------------------------------------------------------------- 1 | # Vendor Dep 2 | 3 | Test for [Issue#4](https://github.com/golang/mock/issues/4). 4 | Also see discussion on [#28](https://github.com/golang/mock/pull/28). 5 | -------------------------------------------------------------------------------- /mockgen/internal/tests/vendor_dep/doc.go: -------------------------------------------------------------------------------- 1 | package vendor_dep 2 | 3 | //go:generate mockgen -package vendor_dep -destination mock.go github.com/golang/mock/mockgen/internal/tests/vendor_dep VendorsDep 4 | //go:generate mockgen -destination source_mock_package/mock.go -source=vendor_dep.go 5 | -------------------------------------------------------------------------------- /mockgen/internal/tests/vendor_dep/mock.go: -------------------------------------------------------------------------------- 1 | // Code generated by MockGen. DO NOT EDIT. 2 | // Source: github.com/golang/mock/mockgen/internal/tests/vendor_dep (interfaces: VendorsDep) 3 | 4 | // Package vendor_dep is a generated GoMock package. 5 | package vendor_dep 6 | 7 | import ( 8 | reflect "reflect" 9 | 10 | gomock "github.com/golang/mock/gomock" 11 | present "golang.org/x/tools/present" 12 | ) 13 | 14 | // MockVendorsDep is a mock of VendorsDep interface. 15 | type MockVendorsDep struct { 16 | ctrl *gomock.Controller 17 | recorder *MockVendorsDepMockRecorder 18 | } 19 | 20 | // MockVendorsDepMockRecorder is the mock recorder for MockVendorsDep. 21 | type MockVendorsDepMockRecorder struct { 22 | mock *MockVendorsDep 23 | } 24 | 25 | // NewMockVendorsDep creates a new mock instance. 26 | func NewMockVendorsDep(ctrl *gomock.Controller) *MockVendorsDep { 27 | mock := &MockVendorsDep{ctrl: ctrl} 28 | mock.recorder = &MockVendorsDepMockRecorder{mock} 29 | return mock 30 | } 31 | 32 | // EXPECT returns an object that allows the caller to indicate expected use. 33 | func (m *MockVendorsDep) EXPECT() *MockVendorsDepMockRecorder { 34 | return m.recorder 35 | } 36 | 37 | // Foo mocks base method. 38 | func (m *MockVendorsDep) Foo() present.Elem { 39 | m.ctrl.T.Helper() 40 | ret := m.ctrl.Call(m, "Foo") 41 | ret0, _ := ret[0].(present.Elem) 42 | return ret0 43 | } 44 | 45 | // Foo indicates an expected call of Foo. 46 | func (mr *MockVendorsDepMockRecorder) Foo() *gomock.Call { 47 | mr.mock.ctrl.T.Helper() 48 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Foo", reflect.TypeOf((*MockVendorsDep)(nil).Foo)) 49 | } 50 | -------------------------------------------------------------------------------- /mockgen/internal/tests/vendor_dep/source_mock_package/mock.go: -------------------------------------------------------------------------------- 1 | // Code generated by MockGen. DO NOT EDIT. 2 | // Source: vendor_dep.go 3 | 4 | // Package mock_vendor_dep is a generated GoMock package. 5 | package mock_vendor_dep 6 | 7 | import ( 8 | reflect "reflect" 9 | 10 | gomock "github.com/golang/mock/gomock" 11 | present "golang.org/x/tools/present" 12 | ) 13 | 14 | // MockVendorsDep is a mock of VendorsDep interface. 15 | type MockVendorsDep struct { 16 | ctrl *gomock.Controller 17 | recorder *MockVendorsDepMockRecorder 18 | } 19 | 20 | // MockVendorsDepMockRecorder is the mock recorder for MockVendorsDep. 21 | type MockVendorsDepMockRecorder struct { 22 | mock *MockVendorsDep 23 | } 24 | 25 | // NewMockVendorsDep creates a new mock instance. 26 | func NewMockVendorsDep(ctrl *gomock.Controller) *MockVendorsDep { 27 | mock := &MockVendorsDep{ctrl: ctrl} 28 | mock.recorder = &MockVendorsDepMockRecorder{mock} 29 | return mock 30 | } 31 | 32 | // EXPECT returns an object that allows the caller to indicate expected use. 33 | func (m *MockVendorsDep) EXPECT() *MockVendorsDepMockRecorder { 34 | return m.recorder 35 | } 36 | 37 | // Foo mocks base method. 38 | func (m *MockVendorsDep) Foo() present.Elem { 39 | m.ctrl.T.Helper() 40 | ret := m.ctrl.Call(m, "Foo") 41 | ret0, _ := ret[0].(present.Elem) 42 | return ret0 43 | } 44 | 45 | // Foo indicates an expected call of Foo. 46 | func (mr *MockVendorsDepMockRecorder) Foo() *gomock.Call { 47 | mr.mock.ctrl.T.Helper() 48 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Foo", reflect.TypeOf((*MockVendorsDep)(nil).Foo)) 49 | } 50 | -------------------------------------------------------------------------------- /mockgen/internal/tests/vendor_dep/vendor_dep.go: -------------------------------------------------------------------------------- 1 | package vendor_dep 2 | 3 | import "golang.org/x/tools/present" 4 | 5 | type VendorsDep interface { 6 | Foo() present.Elem 7 | } 8 | -------------------------------------------------------------------------------- /mockgen/internal/tests/vendor_pkg/README.md: -------------------------------------------------------------------------------- 1 | # Vendor Pkg 2 | 3 | Test for [Issue#4](https://github.com/golang/mock/issues/4). 4 | -------------------------------------------------------------------------------- /mockgen/internal/tests/vendor_pkg/doc.go: -------------------------------------------------------------------------------- 1 | package vendor_pkg 2 | 3 | //go:generate mockgen -destination mock.go -package vendor_pkg golang.org/x/tools/present Elem 4 | -------------------------------------------------------------------------------- /mockgen/internal/tests/vendor_pkg/mock.go: -------------------------------------------------------------------------------- 1 | // Code generated by MockGen. DO NOT EDIT. 2 | // Source: golang.org/x/tools/present (interfaces: Elem) 3 | 4 | // Package vendor_pkg is a generated GoMock package. 5 | package vendor_pkg 6 | 7 | import ( 8 | reflect "reflect" 9 | 10 | gomock "github.com/golang/mock/gomock" 11 | ) 12 | 13 | // MockElem is a mock of Elem interface. 14 | type MockElem struct { 15 | ctrl *gomock.Controller 16 | recorder *MockElemMockRecorder 17 | } 18 | 19 | // MockElemMockRecorder is the mock recorder for MockElem. 20 | type MockElemMockRecorder struct { 21 | mock *MockElem 22 | } 23 | 24 | // NewMockElem creates a new mock instance. 25 | func NewMockElem(ctrl *gomock.Controller) *MockElem { 26 | mock := &MockElem{ctrl: ctrl} 27 | mock.recorder = &MockElemMockRecorder{mock} 28 | return mock 29 | } 30 | 31 | // EXPECT returns an object that allows the caller to indicate expected use. 32 | func (m *MockElem) EXPECT() *MockElemMockRecorder { 33 | return m.recorder 34 | } 35 | 36 | // TemplateName mocks base method. 37 | func (m *MockElem) TemplateName() string { 38 | m.ctrl.T.Helper() 39 | ret := m.ctrl.Call(m, "TemplateName") 40 | ret0, _ := ret[0].(string) 41 | return ret0 42 | } 43 | 44 | // TemplateName indicates an expected call of TemplateName. 45 | func (mr *MockElemMockRecorder) TemplateName() *gomock.Call { 46 | mr.mock.ctrl.T.Helper() 47 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "TemplateName", reflect.TypeOf((*MockElem)(nil).TemplateName)) 48 | } 49 | -------------------------------------------------------------------------------- /mockgen/model/model_test.go: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | ) 7 | 8 | func TestImpPath(t *testing.T) { 9 | nonVendor := "github.com/foo/bar" 10 | if nonVendor != impPath(nonVendor) { 11 | t.Errorf("") 12 | 13 | } 14 | testCases := []struct { 15 | input string 16 | want string 17 | }{ 18 | {"foo/bar", "foo/bar"}, 19 | {"vendor/foo/bar", "foo/bar"}, 20 | {"vendor/foo/vendor/bar", "bar"}, 21 | {"/vendor/foo/bar", "foo/bar"}, 22 | {"qux/vendor/foo/bar", "foo/bar"}, 23 | {"qux/vendor/foo/vendor/bar", "bar"}, 24 | {"govendor/foo", "govendor/foo"}, 25 | {"foo/govendor/bar", "foo/govendor/bar"}, 26 | {"vendors/foo", "vendors/foo"}, 27 | {"foo/vendors/bar", "foo/vendors/bar"}, 28 | } 29 | for _, tc := range testCases { 30 | t.Run(fmt.Sprintf("input %s", tc.input), func(t *testing.T) { 31 | if got := impPath(tc.input); got != tc.want { 32 | t.Errorf("got %s; want %s", got, tc.want) 33 | } 34 | }) 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /mockgen/parse_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "go/parser" 5 | "go/token" 6 | "testing" 7 | ) 8 | 9 | func TestFileParser_ParseFile(t *testing.T) { 10 | fs := token.NewFileSet() 11 | file, err := parser.ParseFile(fs, "internal/tests/custom_package_name/greeter/greeter.go", nil, 0) 12 | if err != nil { 13 | t.Fatalf("Unexpected error: %v", err) 14 | } 15 | 16 | p := fileParser{ 17 | fileSet: fs, 18 | imports: make(map[string]importedPackage), 19 | importedInterfaces: newInterfaceCache(), 20 | } 21 | 22 | pkg, err := p.parseFile("", file) 23 | if err != nil { 24 | t.Fatalf("Unexpected error: %v", err) 25 | } 26 | 27 | checkGreeterImports(t, p.imports) 28 | 29 | expectedName := "greeter" 30 | if pkg.Name != expectedName { 31 | t.Fatalf("Expected name to be %v but got %v", expectedName, pkg.Name) 32 | } 33 | 34 | expectedInterfaceName := "InputMaker" 35 | if pkg.Interfaces[0].Name != expectedInterfaceName { 36 | t.Fatalf("Expected interface name to be %v but got %v", expectedInterfaceName, pkg.Interfaces[0].Name) 37 | } 38 | } 39 | 40 | func TestFileParser_ParsePackage(t *testing.T) { 41 | fs := token.NewFileSet() 42 | _, err := parser.ParseFile(fs, "internal/tests/custom_package_name/greeter/greeter.go", nil, 0) 43 | if err != nil { 44 | t.Fatalf("Unexpected error: %v", err) 45 | } 46 | 47 | p := fileParser{ 48 | fileSet: fs, 49 | imports: make(map[string]importedPackage), 50 | importedInterfaces: newInterfaceCache(), 51 | } 52 | 53 | newP, err := p.parsePackage("github.com/golang/mock/mockgen/internal/tests/custom_package_name/greeter") 54 | if err != nil { 55 | t.Fatalf("Unexpected error: %v", err) 56 | } 57 | 58 | checkGreeterImports(t, newP.imports) 59 | } 60 | 61 | func TestImportsOfFile(t *testing.T) { 62 | fs := token.NewFileSet() 63 | file, err := parser.ParseFile(fs, "internal/tests/custom_package_name/greeter/greeter.go", nil, 0) 64 | if err != nil { 65 | t.Fatalf("Unexpected error: %v", err) 66 | } 67 | 68 | imports, _ := importsOfFile(file) 69 | checkGreeterImports(t, imports) 70 | } 71 | 72 | func checkGreeterImports(t *testing.T, imports map[string]importedPackage) { 73 | // check that imports have stdlib package "fmt" 74 | if fmtPackage, ok := imports["fmt"]; !ok { 75 | t.Errorf("Expected imports to have key \"fmt\"") 76 | } else { 77 | expectedFmtPackage := "fmt" 78 | if fmtPackage.Path() != expectedFmtPackage { 79 | t.Errorf("Expected fmt key to have value %s but got %s", expectedFmtPackage, fmtPackage.Path()) 80 | } 81 | } 82 | 83 | // check that imports have package named "validator" 84 | if validatorPackage, ok := imports["validator"]; !ok { 85 | t.Errorf("Expected imports to have key \"fmt\"") 86 | } else { 87 | expectedValidatorPackage := "github.com/golang/mock/mockgen/internal/tests/custom_package_name/validator" 88 | if validatorPackage.Path() != expectedValidatorPackage { 89 | t.Errorf("Expected validator key to have value %s but got %s", expectedValidatorPackage, validatorPackage.Path()) 90 | } 91 | } 92 | 93 | // check that imports have package named "client" 94 | if clientPackage, ok := imports["client"]; !ok { 95 | t.Errorf("Expected imports to have key \"client\"") 96 | } else { 97 | expectedClientPackage := "github.com/golang/mock/mockgen/internal/tests/custom_package_name/client/v1" 98 | if clientPackage.Path() != expectedClientPackage { 99 | t.Errorf("Expected client key to have value %s but got %s", expectedClientPackage, clientPackage.Path()) 100 | } 101 | } 102 | 103 | // check that imports don't have package named "v1" 104 | if _, ok := imports["v1"]; ok { 105 | t.Errorf("Expected import not to have key \"v1\"") 106 | } 107 | } 108 | 109 | func Benchmark_parseFile(b *testing.B) { 110 | source := "internal/tests/performance/big_interface/big_interface.go" 111 | for n := 0; n < b.N; n++ { 112 | sourceMode(source) 113 | } 114 | } 115 | 116 | func TestParseArrayWithConstLength(t *testing.T) { 117 | fs := token.NewFileSet() 118 | srcDir := "internal/tests/const_array_length/input.go" 119 | 120 | file, err := parser.ParseFile(fs, srcDir, nil, 0) 121 | if err != nil { 122 | t.Fatalf("Unexpected error: %v", err) 123 | } 124 | 125 | p := fileParser{ 126 | fileSet: fs, 127 | imports: make(map[string]importedPackage), 128 | importedInterfaces: newInterfaceCache(), 129 | auxInterfaces: newInterfaceCache(), 130 | srcDir: srcDir, 131 | } 132 | 133 | pkg, err := p.parseFile("", file) 134 | if err != nil { 135 | t.Fatalf("Unexpected error: %v", err) 136 | } 137 | 138 | expects := []string{"[2]int", "[2]int", "[127]int", "[3]int", "[3]int", "[7]int"} 139 | for i, e := range expects { 140 | got := pkg.Interfaces[0].Methods[i].Out[0].Type.String(nil, "") 141 | if got != e { 142 | t.Fatalf("got %v; expected %v", got, e) 143 | } 144 | } 145 | } 146 | -------------------------------------------------------------------------------- /mockgen/reflect.go: -------------------------------------------------------------------------------- 1 | // Copyright 2012 Google Inc. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package main 16 | 17 | // This file contains the model construction by reflection. 18 | 19 | import ( 20 | "bytes" 21 | "encoding/gob" 22 | "flag" 23 | "fmt" 24 | "go/build" 25 | "io" 26 | "io/ioutil" 27 | "log" 28 | "os" 29 | "os/exec" 30 | "path/filepath" 31 | "runtime" 32 | "strings" 33 | "text/template" 34 | 35 | "github.com/golang/mock/mockgen/model" 36 | ) 37 | 38 | var ( 39 | progOnly = flag.Bool("prog_only", false, "(reflect mode) Only generate the reflection program; write it to stdout and exit.") 40 | execOnly = flag.String("exec_only", "", "(reflect mode) If set, execute this reflection program.") 41 | buildFlags = flag.String("build_flags", "", "(reflect mode) Additional flags for go build.") 42 | ) 43 | 44 | // reflectMode generates mocks via reflection on an interface. 45 | func reflectMode(importPath string, symbols []string) (*model.Package, error) { 46 | if *execOnly != "" { 47 | return run(*execOnly) 48 | } 49 | 50 | program, err := writeProgram(importPath, symbols) 51 | if err != nil { 52 | return nil, err 53 | } 54 | 55 | if *progOnly { 56 | if _, err := os.Stdout.Write(program); err != nil { 57 | return nil, err 58 | } 59 | os.Exit(0) 60 | } 61 | 62 | wd, _ := os.Getwd() 63 | 64 | // Try to run the reflection program in the current working directory. 65 | if p, err := runInDir(program, wd); err == nil { 66 | return p, nil 67 | } 68 | 69 | // Try to run the program in the same directory as the input package. 70 | if p, err := build.Import(importPath, wd, build.FindOnly); err == nil { 71 | dir := p.Dir 72 | if p, err := runInDir(program, dir); err == nil { 73 | return p, nil 74 | } 75 | } 76 | 77 | // Try to run it in a standard temp directory. 78 | return runInDir(program, "") 79 | } 80 | 81 | func writeProgram(importPath string, symbols []string) ([]byte, error) { 82 | var program bytes.Buffer 83 | data := reflectData{ 84 | ImportPath: importPath, 85 | Symbols: symbols, 86 | } 87 | if err := reflectProgram.Execute(&program, &data); err != nil { 88 | return nil, err 89 | } 90 | return program.Bytes(), nil 91 | } 92 | 93 | // run the given program and parse the output as a model.Package. 94 | func run(program string) (*model.Package, error) { 95 | f, err := ioutil.TempFile("", "") 96 | if err != nil { 97 | return nil, err 98 | } 99 | 100 | filename := f.Name() 101 | defer os.Remove(filename) 102 | if err := f.Close(); err != nil { 103 | return nil, err 104 | } 105 | 106 | // Run the program. 107 | cmd := exec.Command(program, "-output", filename) 108 | cmd.Stdout = os.Stdout 109 | cmd.Stderr = os.Stderr 110 | if err := cmd.Run(); err != nil { 111 | return nil, err 112 | } 113 | 114 | f, err = os.Open(filename) 115 | if err != nil { 116 | return nil, err 117 | } 118 | 119 | // Process output. 120 | var pkg model.Package 121 | if err := gob.NewDecoder(f).Decode(&pkg); err != nil { 122 | return nil, err 123 | } 124 | 125 | if err := f.Close(); err != nil { 126 | return nil, err 127 | } 128 | 129 | return &pkg, nil 130 | } 131 | 132 | // runInDir writes the given program into the given dir, runs it there, and 133 | // parses the output as a model.Package. 134 | func runInDir(program []byte, dir string) (*model.Package, error) { 135 | // We use TempDir instead of TempFile so we can control the filename. 136 | tmpDir, err := ioutil.TempDir(dir, "gomock_reflect_") 137 | if err != nil { 138 | return nil, err 139 | } 140 | defer func() { 141 | if err := os.RemoveAll(tmpDir); err != nil { 142 | log.Printf("failed to remove temp directory: %s", err) 143 | } 144 | }() 145 | const progSource = "prog.go" 146 | var progBinary = "prog.bin" 147 | if runtime.GOOS == "windows" { 148 | // Windows won't execute a program unless it has a ".exe" suffix. 149 | progBinary += ".exe" 150 | } 151 | 152 | if err := ioutil.WriteFile(filepath.Join(tmpDir, progSource), program, 0600); err != nil { 153 | return nil, err 154 | } 155 | 156 | cmdArgs := []string{} 157 | cmdArgs = append(cmdArgs, "build") 158 | if *buildFlags != "" { 159 | cmdArgs = append(cmdArgs, strings.Split(*buildFlags, " ")...) 160 | } 161 | cmdArgs = append(cmdArgs, "-o", progBinary, progSource) 162 | 163 | // Build the program. 164 | buf := bytes.NewBuffer(nil) 165 | cmd := exec.Command("go", cmdArgs...) 166 | cmd.Dir = tmpDir 167 | cmd.Stdout = os.Stdout 168 | cmd.Stderr = io.MultiWriter(os.Stderr, buf) 169 | if err := cmd.Run(); err != nil { 170 | sErr := buf.String() 171 | if strings.Contains(sErr, `cannot find package "."`) && 172 | strings.Contains(sErr, "github.com/golang/mock/mockgen/model") { 173 | fmt.Fprint(os.Stderr, "Please reference the steps in the README to fix this error:\n\thttps://github.com/golang/mock#reflect-vendoring-error.\n") 174 | return nil, err 175 | } 176 | return nil, err 177 | } 178 | 179 | return run(filepath.Join(tmpDir, progBinary)) 180 | } 181 | 182 | type reflectData struct { 183 | ImportPath string 184 | Symbols []string 185 | } 186 | 187 | // This program reflects on an interface value, and prints the 188 | // gob encoding of a model.Package to standard output. 189 | // JSON doesn't work because of the model.Type interface. 190 | var reflectProgram = template.Must(template.New("program").Parse(` 191 | package main 192 | 193 | import ( 194 | "encoding/gob" 195 | "flag" 196 | "fmt" 197 | "os" 198 | "path" 199 | "reflect" 200 | 201 | "github.com/golang/mock/mockgen/model" 202 | 203 | pkg_ {{printf "%q" .ImportPath}} 204 | ) 205 | 206 | var output = flag.String("output", "", "The output file name, or empty to use stdout.") 207 | 208 | func main() { 209 | flag.Parse() 210 | 211 | its := []struct{ 212 | sym string 213 | typ reflect.Type 214 | }{ 215 | {{range .Symbols}} 216 | { {{printf "%q" .}}, reflect.TypeOf((*pkg_.{{.}})(nil)).Elem()}, 217 | {{end}} 218 | } 219 | pkg := &model.Package{ 220 | // NOTE: This behaves contrary to documented behaviour if the 221 | // package name is not the final component of the import path. 222 | // The reflect package doesn't expose the package name, though. 223 | Name: path.Base({{printf "%q" .ImportPath}}), 224 | } 225 | 226 | for _, it := range its { 227 | intf, err := model.InterfaceFromInterfaceType(it.typ) 228 | if err != nil { 229 | fmt.Fprintf(os.Stderr, "Reflection: %v\n", err) 230 | os.Exit(1) 231 | } 232 | intf.Name = it.sym 233 | pkg.Interfaces = append(pkg.Interfaces, intf) 234 | } 235 | 236 | outfile := os.Stdout 237 | if len(*output) != 0 { 238 | var err error 239 | outfile, err = os.Create(*output) 240 | if err != nil { 241 | fmt.Fprintf(os.Stderr, "failed to open output file %q", *output) 242 | } 243 | defer func() { 244 | if err := outfile.Close(); err != nil { 245 | fmt.Fprintf(os.Stderr, "failed to close output file %q", *output) 246 | os.Exit(1) 247 | } 248 | }() 249 | } 250 | 251 | if err := gob.NewEncoder(outfile).Encode(pkg); err != nil { 252 | fmt.Fprintf(os.Stderr, "gob encode: %v\n", err) 253 | os.Exit(1) 254 | } 255 | } 256 | `)) 257 | -------------------------------------------------------------------------------- /mockgen/version.go: -------------------------------------------------------------------------------- 1 | // Copyright 2022 Google LLC 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package main 16 | 17 | import ( 18 | "fmt" 19 | "log" 20 | "runtime/debug" 21 | ) 22 | 23 | func printModuleVersion() { 24 | if bi, exists := debug.ReadBuildInfo(); exists { 25 | fmt.Println(bi.Main.Version) 26 | } else { 27 | log.Printf("No version information found. Make sure to use " + 28 | "GO111MODULE=on when running 'go get' in order to use specific " + 29 | "version of the binary.") 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /sample/README.md: -------------------------------------------------------------------------------- 1 | # Samples 2 | 3 | This directory contains an example of a package containing a non-trivial 4 | interface that can be mocked with GoMock. The interesting files are: 5 | 6 | * `user.go`: Source code for the sample package, containing interfaces to be 7 | mocked. This file depends on the packages named imp[1-4] for various things. 8 | 9 | * `user_test.go`: A test for the sample package, in which mocks of the 10 | interfaces from `user.go` are used. This demonstrates how to create mock 11 | objects, set up expectations, and so on. 12 | 13 | * `mock_user_test.go`: The generated mock code. See ../gomock/matchers.go 14 | for the `go:generate` command used to generate it. 15 | 16 | To run the test, 17 | 18 | ```bash 19 | go test github.com/golang/mock/sample 20 | ``` 21 | -------------------------------------------------------------------------------- /sample/concurrent/concurrent.go: -------------------------------------------------------------------------------- 1 | // Package concurrent demonstrates how to use gomock with goroutines. 2 | package concurrent 3 | 4 | //go:generate mockgen -destination mock/concurrent_mock.go github.com/golang/mock/sample/concurrent Math 5 | 6 | type Math interface { 7 | Sum(a, b int) int 8 | } 9 | -------------------------------------------------------------------------------- /sample/concurrent/concurrent_test.go: -------------------------------------------------------------------------------- 1 | package concurrent 2 | 3 | import ( 4 | "testing" 5 | 6 | "context" 7 | 8 | "github.com/golang/mock/gomock" 9 | 10 | mock "github.com/golang/mock/sample/concurrent/mock" 11 | ) 12 | 13 | func call(ctx context.Context, m Math) (int, error) { 14 | result := make(chan int) 15 | go func() { 16 | result <- m.Sum(1, 2) 17 | close(result) 18 | }() 19 | select { 20 | case r := <-result: 21 | return r, nil 22 | case <-ctx.Done(): 23 | return 0, ctx.Err() 24 | } 25 | } 26 | 27 | // TestConcurrentFails is expected to fail (and is disabled). It 28 | // demonstrates how to use gomock.WithContext to interrupt the test 29 | // from a different goroutine. 30 | func TestConcurrentFails(t *testing.T) { 31 | t.Skip("Test is expected to fail, remove skip to trying running yourself.") 32 | ctrl, ctx := gomock.WithContext(context.Background(), t) 33 | defer ctrl.Finish() 34 | m := mock.NewMockMath(ctrl) 35 | if _, err := call(ctx, m); err != nil { 36 | t.Error("call failed:", err) 37 | } 38 | } 39 | 40 | func TestConcurrentWorks(t *testing.T) { 41 | ctrl, ctx := gomock.WithContext(context.Background(), t) 42 | defer ctrl.Finish() 43 | m := mock.NewMockMath(ctrl) 44 | m.EXPECT().Sum(1, 2).Return(3) 45 | if _, err := call(ctx, m); err != nil { 46 | t.Error("call failed:", err) 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /sample/concurrent/mock/concurrent_mock.go: -------------------------------------------------------------------------------- 1 | // Code generated by MockGen. DO NOT EDIT. 2 | // Source: github.com/golang/mock/sample/concurrent (interfaces: Math) 3 | 4 | // Package mock_concurrent is a generated GoMock package. 5 | package mock_concurrent 6 | 7 | import ( 8 | reflect "reflect" 9 | 10 | gomock "github.com/golang/mock/gomock" 11 | ) 12 | 13 | // MockMath is a mock of Math interface. 14 | type MockMath struct { 15 | ctrl *gomock.Controller 16 | recorder *MockMathMockRecorder 17 | } 18 | 19 | // MockMathMockRecorder is the mock recorder for MockMath. 20 | type MockMathMockRecorder struct { 21 | mock *MockMath 22 | } 23 | 24 | // NewMockMath creates a new mock instance. 25 | func NewMockMath(ctrl *gomock.Controller) *MockMath { 26 | mock := &MockMath{ctrl: ctrl} 27 | mock.recorder = &MockMathMockRecorder{mock} 28 | return mock 29 | } 30 | 31 | // EXPECT returns an object that allows the caller to indicate expected use. 32 | func (m *MockMath) EXPECT() *MockMathMockRecorder { 33 | return m.recorder 34 | } 35 | 36 | // Sum mocks base method. 37 | func (m *MockMath) Sum(arg0, arg1 int) int { 38 | m.ctrl.T.Helper() 39 | ret := m.ctrl.Call(m, "Sum", arg0, arg1) 40 | ret0, _ := ret[0].(int) 41 | return ret0 42 | } 43 | 44 | // Sum indicates an expected call of Sum. 45 | func (mr *MockMathMockRecorder) Sum(arg0, arg1 interface{}) *gomock.Call { 46 | mr.mock.ctrl.T.Helper() 47 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Sum", reflect.TypeOf((*MockMath)(nil).Sum), arg0, arg1) 48 | } 49 | -------------------------------------------------------------------------------- /sample/imp1/imp1.go: -------------------------------------------------------------------------------- 1 | package imp1 2 | 3 | import "bufio" 4 | 5 | type Imp1 struct{} 6 | 7 | type ImpT int 8 | 9 | type ForeignEmbedded interface { 10 | // The return value here also makes sure that 11 | // the generated mock picks up the "bufio" import. 12 | ForeignEmbeddedMethod() *bufio.Reader 13 | 14 | // This method uses a type in this package, 15 | // which should be qualified when this interface is embedded. 16 | ImplicitPackage(s string, t ImpT, st []ImpT, pt *ImpT, ct chan ImpT) 17 | } 18 | -------------------------------------------------------------------------------- /sample/imp2/imp2.go: -------------------------------------------------------------------------------- 1 | package imp2 2 | 3 | type Imp2 struct{} 4 | -------------------------------------------------------------------------------- /sample/imp3/imp3.go: -------------------------------------------------------------------------------- 1 | package imp3 2 | 3 | type Imp3 struct{} 4 | -------------------------------------------------------------------------------- /sample/imp4/imp4.go: -------------------------------------------------------------------------------- 1 | package imp_four 2 | 3 | type Imp4 struct{} 4 | -------------------------------------------------------------------------------- /sample/user.go: -------------------------------------------------------------------------------- 1 | // Package user is an example package with an interface. 2 | package user 3 | 4 | //go:generate mockgen -destination mock_user_test.go -package user_test github.com/golang/mock/sample Index,Embed,Embedded 5 | 6 | // Random bunch of imports to test mockgen. 7 | import ( 8 | "io" 9 | 10 | btz "bytes" 11 | "hash" 12 | "log" 13 | "net" 14 | "net/http" 15 | 16 | // Two imports with the same base name. 17 | t1 "html/template" 18 | 19 | t2 "text/template" 20 | 21 | "github.com/golang/mock/sample/imp1" 22 | 23 | // Dependencies outside the standard library. 24 | 25 | renamed2 "github.com/golang/mock/sample/imp2" 26 | 27 | . "github.com/golang/mock/sample/imp3" 28 | 29 | imp_four "github.com/golang/mock/sample/imp4" 30 | ) 31 | 32 | // calls itself "imp_four" 33 | 34 | // A bizarre interface to test corner cases in mockgen. 35 | // This would normally be in its own file or package, 36 | // separate from the user of it (e.g. io.Reader). 37 | type Index interface { 38 | Get(key string) interface{} 39 | GetTwo(key1, key2 string) (v1, v2 interface{}) 40 | Put(key string, value interface{}) 41 | 42 | // Check that imports are handled correctly. 43 | Summary(buf *btz.Buffer, w io.Writer) 44 | Other() hash.Hash 45 | Templates(a t1.CSS, b t2.FuncMap) 46 | 47 | // A method with an anonymous argument. 48 | Anon(string) 49 | 50 | // Methods using foreign types outside the standard library. 51 | ForeignOne(imp1.Imp1) 52 | ForeignTwo(renamed2.Imp2) 53 | ForeignThree(Imp3) 54 | ForeignFour(imp_four.Imp4) 55 | 56 | // A method that returns a nillable type. 57 | NillableRet() error 58 | // A method that returns a non-interface type. 59 | ConcreteRet() chan<- bool 60 | 61 | // Methods with an ellipsis argument. 62 | Ellip(fmt string, args ...interface{}) 63 | EllipOnly(...string) 64 | 65 | // A method with a pointer argument that we will set. 66 | Ptr(arg *int) 67 | 68 | // A method with a slice argument and an array return. 69 | Slice(a []int, b []byte) [3]int 70 | 71 | // A method with channel arguments. 72 | Chan(a chan int, b chan<- hash.Hash) 73 | 74 | // A method with a function argument. 75 | Func(f func(http.Request) (int, bool)) 76 | 77 | // A method with a map argument. 78 | Map(a map[int]hash.Hash) 79 | 80 | // Methods with an unnamed empty struct argument. 81 | Struct(a struct{}) // not so likely 82 | StructChan(a chan struct{}) // a bit more common 83 | } 84 | 85 | // An interface with an embedded interface. 86 | type Embed interface { 87 | RegularMethod() 88 | Embedded 89 | imp1.ForeignEmbedded 90 | } 91 | 92 | type Embedded interface { 93 | EmbeddedMethod() 94 | } 95 | 96 | // some random use of another package that isn't needed by the interface. 97 | var _ net.Addr 98 | 99 | // A function that we will test that uses the above interface. 100 | // It takes a list of keys and values, and puts them in the index. 101 | func Remember(index Index, keys []string, values []interface{}) { 102 | for i, k := range keys { 103 | index.Put(k, values[i]) 104 | } 105 | err := index.NillableRet() 106 | if err != nil { 107 | log.Fatalf("Woah! %v", err) 108 | } 109 | if len(keys) > 0 && keys[0] == "a" { 110 | index.Ellip("%d", 0, 1, 1, 2, 3) 111 | index.Ellip("%d", 1, 3, 6, 10, 15) 112 | index.EllipOnly("arg") 113 | } 114 | } 115 | 116 | func GrabPointer(index Index) int { 117 | var a int 118 | index.Ptr(&a) 119 | return a 120 | } 121 | -------------------------------------------------------------------------------- /sample/user_test.go: -------------------------------------------------------------------------------- 1 | // A test that uses a mock. 2 | package user_test 3 | 4 | import ( 5 | "testing" 6 | 7 | "github.com/golang/mock/gomock" 8 | user "github.com/golang/mock/sample" 9 | "github.com/golang/mock/sample/imp1" 10 | ) 11 | 12 | func TestRemember(t *testing.T) { 13 | ctrl := gomock.NewController(t) 14 | defer ctrl.Finish() 15 | 16 | mockIndex := NewMockIndex(ctrl) 17 | mockIndex.EXPECT().Put("a", 1) // literals work 18 | mockIndex.EXPECT().Put("b", gomock.Eq(2)) // matchers work too 19 | 20 | // NillableRet returns error. Not declaring it should result in a nil return. 21 | mockIndex.EXPECT().NillableRet() 22 | // Calls that returns something assignable to the return type. 23 | boolc := make(chan bool) 24 | // In this case, "chan bool" is assignable to "chan<- bool". 25 | mockIndex.EXPECT().ConcreteRet().Return(boolc) 26 | // In this case, nil is assignable to "chan<- bool". 27 | mockIndex.EXPECT().ConcreteRet().Return(nil) 28 | 29 | // Should be able to place expectations on variadic methods. 30 | mockIndex.EXPECT().Ellip("%d", 0, 1, 1, 2, 3) // direct args 31 | tri := []interface{}{1, 3, 6, 10, 15} 32 | mockIndex.EXPECT().Ellip("%d", tri...) // args from slice 33 | mockIndex.EXPECT().EllipOnly(gomock.Eq("arg")) 34 | 35 | user.Remember(mockIndex, []string{"a", "b"}, []interface{}{1, 2}) 36 | // Check the ConcreteRet calls. 37 | if c := mockIndex.ConcreteRet(); c != boolc { 38 | t.Errorf("ConcreteRet: got %v, want %v", c, boolc) 39 | } 40 | if c := mockIndex.ConcreteRet(); c != nil { 41 | t.Errorf("ConcreteRet: got %v, want nil", c) 42 | } 43 | 44 | // Try one with an action. 45 | calledString := "" 46 | mockIndex.EXPECT().Put(gomock.Any(), gomock.Any()).Do(func(key string, _ interface{}) { 47 | calledString = key 48 | }) 49 | mockIndex.EXPECT().NillableRet() 50 | user.Remember(mockIndex, []string{"blah"}, []interface{}{7}) 51 | if calledString != "blah" { 52 | t.Fatalf(`Uh oh. %q != "blah"`, calledString) 53 | } 54 | 55 | // Use Do with a nil arg. 56 | mockIndex.EXPECT().Put("nil-key", gomock.Any()).Do(func(key string, value interface{}) { 57 | if value != nil { 58 | t.Errorf("Put did not pass through nil; got %v", value) 59 | } 60 | }) 61 | mockIndex.EXPECT().NillableRet() 62 | user.Remember(mockIndex, []string{"nil-key"}, []interface{}{nil}) 63 | } 64 | 65 | func TestVariadicFunction(t *testing.T) { 66 | ctrl := gomock.NewController(t) 67 | defer ctrl.Finish() 68 | 69 | mockIndex := NewMockIndex(ctrl) 70 | mockIndex.EXPECT().Ellip("%d", 5, 6, 7, 8).Do(func(format string, nums ...int) { 71 | sum := 0 72 | for _, value := range nums { 73 | sum += value 74 | } 75 | if sum != 26 { 76 | t.Errorf("Expected 26, got %d", sum) 77 | } 78 | }) 79 | mockIndex.EXPECT().Ellip("%d", gomock.Any()).Do(func(format string, nums ...int) { 80 | sum := 0 81 | for _, value := range nums { 82 | sum += value 83 | } 84 | if sum != 10 { 85 | t.Errorf("Expected 10, got %d", sum) 86 | } 87 | }) 88 | mockIndex.EXPECT().Ellip("%d", gomock.Any()).Do(func(format string, nums ...int) { 89 | sum := 0 90 | for _, value := range nums { 91 | sum += value 92 | } 93 | if sum != 0 { 94 | t.Errorf("Expected 0, got %d", sum) 95 | } 96 | }) 97 | mockIndex.EXPECT().Ellip("%d", gomock.Any()).Do(func(format string, nums ...int) { 98 | sum := 0 99 | for _, value := range nums { 100 | sum += value 101 | } 102 | if sum != 0 { 103 | t.Errorf("Expected 0, got %d", sum) 104 | } 105 | }) 106 | mockIndex.EXPECT().Ellip("%d").Do(func(format string, nums ...int) { 107 | sum := 0 108 | for _, value := range nums { 109 | sum += value 110 | } 111 | if sum != 0 { 112 | t.Errorf("Expected 0, got %d", sum) 113 | } 114 | }) 115 | 116 | mockIndex.Ellip("%d", 1, 2, 3, 4) // Match second matcher. 117 | mockIndex.Ellip("%d", 5, 6, 7, 8) // Match first matcher. 118 | mockIndex.Ellip("%d", 0) 119 | mockIndex.Ellip("%d") 120 | mockIndex.Ellip("%d") 121 | } 122 | 123 | func TestGrabPointer(t *testing.T) { 124 | ctrl := gomock.NewController(t) 125 | defer ctrl.Finish() 126 | 127 | mockIndex := NewMockIndex(ctrl) 128 | mockIndex.EXPECT().Ptr(gomock.Any()).SetArg(0, 7) // set first argument to 7 129 | 130 | i := user.GrabPointer(mockIndex) 131 | if i != 7 { 132 | t.Errorf("Expected 7, got %d", i) 133 | } 134 | } 135 | 136 | func TestEmbeddedInterface(t *testing.T) { 137 | ctrl := gomock.NewController(t) 138 | defer ctrl.Finish() 139 | 140 | mockEmbed := NewMockEmbed(ctrl) 141 | mockEmbed.EXPECT().RegularMethod() 142 | mockEmbed.EXPECT().EmbeddedMethod() 143 | mockEmbed.EXPECT().ForeignEmbeddedMethod() 144 | 145 | mockEmbed.RegularMethod() 146 | mockEmbed.EmbeddedMethod() 147 | var emb imp1.ForeignEmbedded = mockEmbed // also does interface check 148 | emb.ForeignEmbeddedMethod() 149 | } 150 | 151 | func TestExpectTrueNil(t *testing.T) { 152 | // Make sure that passing "nil" to EXPECT (thus as a nil interface value), 153 | // will correctly match a nil concrete type. 154 | ctrl := gomock.NewController(t) 155 | defer ctrl.Finish() 156 | 157 | mockIndex := NewMockIndex(ctrl) 158 | mockIndex.EXPECT().Ptr(nil) // this nil is a nil interface{} 159 | mockIndex.Ptr(nil) // this nil is a nil *int 160 | } 161 | 162 | func TestDoAndReturnSignature(t *testing.T) { 163 | t.Run("wrong number of return args", func(t *testing.T) { 164 | ctrl := gomock.NewController(t) 165 | defer ctrl.Finish() 166 | 167 | mockIndex := NewMockIndex(ctrl) 168 | 169 | mockIndex.EXPECT().Slice(gomock.Any(), gomock.Any()).DoAndReturn( 170 | func(_ []int, _ []byte) {}, 171 | ) 172 | 173 | defer func() { 174 | if r := recover(); r == nil { 175 | t.Error("expected panic") 176 | } 177 | }() 178 | 179 | mockIndex.Slice([]int{0}, []byte("meow")) 180 | }) 181 | 182 | t.Run("wrong type of return arg", func(t *testing.T) { 183 | ctrl := gomock.NewController(t) 184 | defer ctrl.Finish() 185 | 186 | mockIndex := NewMockIndex(ctrl) 187 | 188 | mockIndex.EXPECT().Slice(gomock.Any(), gomock.Any()).DoAndReturn( 189 | func(_ []int, _ []byte) bool { 190 | return true 191 | }) 192 | 193 | mockIndex.Slice([]int{0}, []byte("meow")) 194 | }) 195 | } 196 | --------------------------------------------------------------------------------