{"id":28713500,"url":"https://github.com/go-spring/mock","last_synced_at":"2025-07-06T21:32:33.586Z","repository":{"id":299042647,"uuid":"1001897103","full_name":"go-spring/mock","owner":"go-spring","description":"A modern and type-safe mocking library for Go with full support for generics.","archived":false,"fork":false,"pushed_at":"2025-06-20T14:02:53.000Z","size":85,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-06-21T10:52:07.472Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/go-spring.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2025-06-14T09:15:24.000Z","updated_at":"2025-06-20T14:06:21.000Z","dependencies_parsed_at":"2025-06-14T10:29:36.725Z","dependency_job_id":"095dc635-414d-4d8f-9ad9-47431adbe8bb","html_url":"https://github.com/go-spring/mock","commit_stats":null,"previous_names":["go-spring/mock"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/go-spring/mock","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/go-spring%2Fmock","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/go-spring%2Fmock/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/go-spring%2Fmock/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/go-spring%2Fmock/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/go-spring","download_url":"https://codeload.github.com/go-spring/mock/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/go-spring%2Fmock/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":263975374,"owners_count":23538314,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-06-15T00:10:35.525Z","updated_at":"2025-07-06T21:32:33.581Z","avatar_url":"https://github.com/go-spring.png","language":"Go","funding_links":[],"categories":[],"sub_categories":[],"readme":"# mock\n\n[English](README.md) | [中文](README_CN.md)\n\n**mock** is a modern, type-safe mocking library for the Go programming language, fully supporting generic programming.\nIt provides a simple and easy-to-use interface that helps developers easily create and manage mock objects, thereby\nimproving the quality and efficiency of unit testing. The library is designed to address the lack of type safety and the\ncomplexity of traditional mocking tools in Go.\n\n## Key Features\n\n* **Type Safety**: Utilizes Go 1.18+ generics to ensure compile-time safety and avoid runtime type errors\n* **Multiple Mocking Modes**:\n    * `Handle` Mode: Directly handle function calls\n    * `When/Return` Mode: Conditional mock returns\n* **Flexible Method Matching**: Supports different numbers and types of parameters and return values (up to 5 parameters\n  and 5 return values)\n* **Context Support**: Provides integration with the `context` package, making it easier to test in distributed systems\n* **Auto Reset Functionality**: The `Manager` provides a `Reset` method to easily reset all mockers to their initial\n  state\n* **Detailed Error Messages**: Offers clear error prompts when no matching mock code is found or when multiple matches\n  exist\n\n## Installation Tool\n\n**gsmock** is a tool used to generate Go mock code. You can install it with the following command:\n\n```bash\ngo install github.com/go-spring/mock/gsmock@latest\n```\n\n### Basic Usage\n\n1. **Define an Interface**\n\nFirst, define the interface you want to mock in your project. For example, create a file named `service.go` and add the\nfollowing code:\n\n```go\npackage main\n\ntype Service interface {\n\tSave(r1, r2, r3, r4, r5, r6 int)\n}\n```\n\n2. **Generate Mock Code**\n\nThen, add a `go:generate` directive to the `service.go` file to generate the mock code:\n\n```go\n//go:generate gsmock\n```\n\nYou need to specify an output filename, such as `service_mock.go`, otherwise the output will be printed to the console.\n\n```go\n//go:generate gsmock -o src_mock.go\n```\n\nYou can also specify which interfaces to generate mocks for and which to exclude (prefix the interface name with `!` to\nexclude it).\n\n```go\n//go:generate gsmock -o src_mock.go -i '!RepositoryV2,Repository'\n```\n\n## Usage Example\n\nBelow is a simple usage example:\n\n```go\npackage mock_test\n\nimport (\n\t\"context\"\n\t\"reflect\"\n\t\"testing\"\n\n\t\"github.com/go-spring/mock\"\n\t\"github.com/go-spring/mock/internal/assert\"\n)\n\ntype Trace struct {\n\tTraceId string\n}\n\ntype Request struct {\n\tToken string\n}\n\ntype Response struct {\n\tMessage string\n}\n\ntype Client struct{}\n\nvar clientType = reflect.TypeFor[Client]()\n\nfunc (c *Client) Get(ctx context.Context, req *Request, trace *Trace) (*Response, error) {\n\tif ret, ok := mock.InvokeContext(ctx, clientType, \"Get\", ctx, req, trace); ok {\n\t\treturn mock.Unbox2[*Response, error](ret)\n\t}\n\treturn \u0026Response{Message: \"9:xxx\"}, nil\n}\n\n// MockGet registers a mock implementation for the Get method.\nfunc MockGet(r *mock.Manager) *mock.Mocker32[context.Context, *Request, *Trace, *Response, error] {\n\treturn mock.NewMocker32[context.Context, *Request, *Trace, *Response, error](r, clientType, \"Get\")\n}\n\nfunc TestMockWithContext(t *testing.T) {\n\tvar c Client\n\n\t// Test case: Unmocked\n\t{\n\t\tresp, err := c.Get(t.Context(), \u0026Request{}, \u0026Trace{})\n\t\tassert.Nil(t, err)\n\t\tassert.Equal(t, resp.Message, \"9:xxx\")\n\t}\n\n\tr := mock.NewManager()\n\tctx := r.BindTo(t.Context())\n\n\t// Test case: When \u0026\u0026 Return\n\t{\n\t\tr.Reset()\n\t\tMockGet(r).\n\t\t\tWhen(func(ctx context.Context, req *Request, trace *Trace) bool {\n\t\t\t\treturn req.Token == \"1:abc\"\n\t\t\t}).\n\t\t\tReturn(func() (resp *Response, err error) {\n\t\t\t\treturn \u0026Response{Message: \"1:abc\"}, nil\n\t\t\t})\n\n\t\tresp, err := c.Get(ctx, \u0026Request{Token: \"1:abc\"}, \u0026Trace{})\n\t\tassert.Nil(t, err)\n\t\tassert.Equal(t, resp.Message, \"1:abc\")\n\t}\n\n\t// Test case: Handle\n\t{\n\t\tr.Reset()\n\t\tMockGet(r).\n\t\t\tHandle(func(ctx context.Context, req *Request, trace *Trace) (resp *Response, err error) {\n\t\t\t\treturn \u0026Response{Message: \"4:xyz\"}, nil\n\t\t\t})\n\n\t\tresp, err := c.Get(ctx, \u0026Request{Token: \"4:xyz\"}, \u0026Trace{})\n\t\tassert.Nil(t, err)\n\t\tassert.Equal(t, resp.Message, \"4:xyz\")\n\t}\n\n\t// Test case: Invalid Handle\n\t{\n\t\tr.Reset()\n\t\tMockGet(r).Handle(nil)\n\n\t\tresp, err := c.Get(ctx, \u0026Request{}, \u0026Trace{})\n\t\tassert.Nil(t, err)\n\t\tassert.Equal(t, resp.Message, \"9:xxx\")\n\t}\n}\n\ntype ClientInterface interface {\n\tQuery(req *Request, trace *Trace) (*Response, error)\n}\n\n// MockClient is a mock implementation of ClientInterface.\ntype MockClient struct {\n\tr *mock.Manager\n}\n\nvar mockClientType = reflect.TypeFor[MockClient]()\n\n// NewMockClient creates a new instance of MockClient.\nfunc NewMockClient(r *mock.Manager) *MockClient {\n\treturn \u0026MockClient{r}\n}\n\n// Query mocks the Query method by invoking a registered mock implementation.\nfunc (c *MockClient) Query(req *Request, trace *Trace) (*Response, error) {\n\tif ret, ok := mock.Invoke(c.r, mockClientType, \"Query\", req, trace); ok {\n\t\treturn mock.Unbox2[*Response, error](ret)\n\t}\n\tpanic(\"mock error\")\n}\n\n// MockQuery registers a mock implementation for the Query method.\nfunc (c *MockClient) MockQuery() *mock.Mocker22[*Request, *Trace, *Response, error] {\n\treturn mock.NewMocker22[*Request, *Trace, *Response, error](c.r, mockClientType, \"Query\")\n}\n\nfunc TestMockNoContext(t *testing.T) {\n\tr := mock.NewManager()\n\n\tvar c ClientInterface\n\tmc := NewMockClient(r)\n\tc = mc\n\n\t// Test case: When \u0026\u0026 Return\n\t{\n\t\tr.Reset()\n\t\tmc.MockQuery().\n\t\t\tWhen(func(req *Request, trace *Trace) bool {\n\t\t\t\treturn req.Token == \"1:abc\"\n\t\t\t}).\n\t\t\tReturn(func() (resp *Response, err error) {\n\t\t\t\treturn \u0026Response{Message: \"1:abc\"}, nil\n\t\t\t})\n\n\t\tresp, err := c.Query(\u0026Request{Token: \"1:abc\"}, \u0026Trace{})\n\t\tassert.Nil(t, err)\n\t\tassert.Equal(t, resp.Message, \"1:abc\")\n\t}\n\n\t// Test case: Handle\n\t{\n\t\tr.Reset()\n\t\tmc.MockQuery().\n\t\t\tHandle(func(req *Request, trace *Trace) (resp *Response, err error) {\n\t\t\t\treturn \u0026Response{Message: \"4:xyz\"}, nil\n\t\t\t})\n\n\t\tresp, err := c.Query(\u0026Request{Token: \"4:xyz\"}, \u0026Trace{})\n\t\tassert.Nil(t, err)\n\t\tassert.Equal(t, resp.Message, \"4:xyz\")\n\t}\n\n\t// Test case: Invalid Handle\n\t{\n\t\tr.Reset()\n\t\tmc.MockQuery().Handle(nil)\n\n\t\tassert.Panic(t, func() {\n\t\t\t_, _ = c.Query(\u0026Request{}, \u0026Trace{})\n\t\t}, \"mock error\")\n\t}\n}\n```\n\n## License\n\nThis project is licensed under the Apache License Version 2.0.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgo-spring%2Fmock","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fgo-spring%2Fmock","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgo-spring%2Fmock/lists"}