### Install Moq Tool Source: https://github.com/matryer/moq/blob/main/README.md Install the latest released version of Moq using go install. Requires Go 1.18+. ```bash go install github.com/matryer/moq@latest ``` -------------------------------- ### Install Go Releaser Source: https://github.com/matryer/moq/blob/main/releasing.md Installs Go Releaser using Homebrew. Ensure you have Homebrew installed and configured. ```bash brew install goreleaser/tap/goreleaser ``` -------------------------------- ### Print Moq Version Source: https://context7.com/matryer/moq/llms.txt Print the installed version of the Moq CLI. This is useful for verifying the installation and checking compatibility. ```bash moq -version ``` -------------------------------- ### Generate Mock from Command Line Source: https://github.com/matryer/moq/blob/main/README.md Example of using Moq on the command line to generate mock code for 'MyInterface' into 'mocks_test.go'. ```bash $ moq -out mocks_test.go . MyInterface ``` -------------------------------- ### Generate Mock with goimports Formatter Source: https://context7.com/matryer/moq/llms.txt Generate a mock using the goimports tool for formatting instead of the default gofmt. Ensure goimports is installed. ```bash moq -fmt goimports -out mocks_test.go . MyInterface ``` -------------------------------- ### Test Mock Implementation Source: https://github.com/matryer/moq/blob/main/README.md Example of using a generated mock in a test. Assign behavior to mock functions and assert call counts and captured values. ```go func TestCompleteSignup(t *testing.T) { var sentTo string mockedEmailSender = &EmailSenderMock{ SendFunc: func(to, subject, body string) error { sentTo = to return nil }, } CompleteSignUp("me@email.com", mockedEmailSender) callsToSend := len(mockedEmailSender.SendCalls()) if callsToSend != 1 { t.Errorf("Send was called %d times", callsToSend) } if sentTo != "me@email.com" { t.Errorf("unexpected recipient: %s", sentTo) } } func CompleteSignUp(to string, sender EmailSender) { // TODO: this } ``` -------------------------------- ### Generate Stub Mock Source: https://context7.com/matryer/moq/llms.txt Generate a mock in stub mode. In this mode, unimplemented methods will return zero values instead of panicking, which can be useful for simpler test setups. ```bash moq -stub -out mocks_test.go . MyInterface ``` -------------------------------- ### Execute Release Build Source: https://github.com/matryer/moq/blob/main/releasing.md Runs the Go Releaser build process. Requires the GITHUB_TOKEN environment variable to be set with a personal access token. ```bash GITHUB_TOKEN=xxx goreleaser --clean ``` -------------------------------- ### Moq Command-Line Usage Source: https://github.com/matryer/moq/blob/main/README.md Command-line interface for Moq. Specify source directory, interfaces, and output options. Use -fmt noop to debug formatting errors. ```bash moq [flags] source-dir interface [interface2 [interface3 [...]]] -fmt string go pretty-printer: gofmt, goimports or noop (default gofmt) -out string output file (default stdout) -pkg string package name (default will infer) -rm first remove output file, if it exists -skip-ensure suppress mock implementation check, avoid import cycle if mocks generated outside of the tested package -stub return zero values when no mock implementation is provided, do not panic -version show the version for moq -with-resets generate functions to facilitate resetting calls made to a mock Specifying an alias for the mock is also supported with the format 'interface:alias' Ex: moq -pkg different . MyInterface:MyMock ``` -------------------------------- ### Generate Mock to File Source: https://context7.com/matryer/moq/llms.txt Generate a mock for a specified interface and write the output to a file. This is the most common way to integrate generated mocks into your project. ```bash moq -out mocks_test.go . MyInterface ``` -------------------------------- ### Run go generate Source: https://context7.com/matryer/moq/llms.txt Execute the go generate command to trigger the mock generation process defined by //go:generate directives in your Go source files. ```bash # Run from the package directory (or repo root) go generate ./... # Output: example/mockpersonstore_test.go is created/updated ``` -------------------------------- ### Configure Mock Generation with moq.Config Source: https://context7.com/matryer/moq/llms.txt Use moq.Config to specify options for mock generation, such as the source directory, package name, formatter, stub implementation behavior, skipping interface checks, and enabling reset methods. ```go cfg := moq.Config{ // Required: path to the directory containing the interface source. SrcDir: "./service", // Optional: override the package name in the generated file. // Defaults to the source package name. PkgName: "servicemock", // Optional: code formatter to apply to generated output. // Accepted values: "" or "gofmt" (default), "goimports", "noop" Formatter: "gofmt", // Optional: when true, unimplemented Func fields return zero values // rather than panicking. Safe for partial mock setups. StubImpl: true, // Optional: when true, the compile-time interface-check variable is // omitted. Useful when mocks are generated outside the tested package // to prevent import cycles. SkipEnsure: true, // Optional: when true, generates ResetCalls() and ResetCalls() // methods on each mock struct. WithResets: true, } ``` -------------------------------- ### Programmatic Mock Generation with moq.New Source: https://context7.com/matryer/moq/llms.txt Construct a Mocker instance programmatically using moq.New and moq.Config. This is useful for custom code generation tooling or build pipelines. ```go package main import ( "os" "github.com/matryer/moq/pkg/moq" ) func main() { m, err := moq.New(moq.Config{ SrcDir: "./mypackage", // directory containing the interface PkgName: "mocks", // output package name (empty = infer from source) Formatter: "goimports", // "gofmt" (default), "goimports", or "noop" StubImpl: false, // true = zero-value stubs instead of panic SkipEnsure: false, // true = omit compile-time interface check WithResets: true, // true = emit ResetCalls() helpers }) if err != nil { panic(err) } // Write mock for "MyService" to stdout if err := m.Mock(os.Stdout, "MyService"); err != nil { panic(err) } // Write mocks for multiple interfaces with aliases to a file f, _ := os.Create("mocks_gen.go") defer f.Close() if err := m.Mock(f, "Reader:ReaderMock", "Writer:WriterMock"); err != nil { panic(err) } } ``` -------------------------------- ### go:generate Integration for Mock Generation Source: https://context7.com/matryer/moq/llms.txt Embed mock generation directly into your Go source files using a //go:generate directive. Running 'go generate ./...' will automatically update the mock files. ```go package example import "context" //go:generate moq -out mockpersonstore_test.go . PersonStore // Person represents a real person. type Person struct { ID string Name string Company string Website string } // PersonStore provides access to Person objects. type PersonStore interface { Get(ctx context.Context, id string) (*Person, error) Create(ctx context.Context, person *Person, confirm bool) error } ``` -------------------------------- ### Generate Mocks for Multiple Interfaces Source: https://context7.com/matryer/moq/llms.txt Generate mocks for multiple interfaces in a single command. All generated mocks will be written to the specified output file. ```bash moq -out mocks_test.go . Reader Writer Closer ``` -------------------------------- ### Generate Mock to Stdout Source: https://context7.com/matryer/moq/llms.txt Generate a mock for a specified interface in the current directory and print it to standard output. Useful for piping to other commands or quick checks. ```bash moq . MyInterface ``` -------------------------------- ### Test Go Releaser Configuration Source: https://github.com/matryer/moq/blob/main/releasing.md Tests and verifies changes to the Go Releaser configuration without publishing. Use this to preview release artifacts and configuration. ```bash goreleaser --snapshot --skip=publish --clean ``` -------------------------------- ### Generate Mock with Go Generate Source: https://github.com/matryer/moq/blob/main/README.md Use go:generate directive to invoke Moq for generating mock code. Ensure the interface definition is in the same package. ```go package my //go:generate moq -out myinterface_moq_test.go . MyInterface type MyInterface interface { Method1() error Method2(i int) } ``` -------------------------------- ### Tag and Push Release Source: https://github.com/matryer/moq/blob/main/releasing.md Creates a new Git tag for the release and pushes it to the origin. This is a prerequisite for triggering a release build. ```bash $ git tag -a v0.1.0 -m "release tag." $ git push origin v0.1.0 ``` -------------------------------- ### Generate Mock and Remove Existing File Source: https://context7.com/matryer/moq/llms.txt Generate a mock and automatically remove the existing output file before writing the new one. This ensures a clean generation process. ```bash moq -rm -out mocks_test.go . MyInterface ``` -------------------------------- ### Generate Mock in Different Package Source: https://context7.com/matryer/moq/llms.txt Generate a mock for an interface and specify a different package name for the generated code. This helps in organizing mock files. ```bash moq -pkg mocks . MyInterface ``` -------------------------------- ### Generate Mocks with Zero Values for Unimplemented Methods Source: https://context7.com/matryer/moq/llms.txt Use the `-stub` flag to generate mocks where methods not explicitly implemented return zero values instead of panicking. This is useful for tests that only need to exercise a subset of an interface's methods. ```go // Generate with: moq -stub -out mock_test.go . FileStore // // Only implement the methods relevant to the current test; // all others return zero values safely. mockedFS := &FileStoreMock{ ReadFunc: func(name string) ([]byte, error) { return []byte("file contents"), nil }, // WriteFunc is intentionally left nil — stub mode returns ("", nil) for it } data, err := mockedFS.Read("config.yaml") fmt.Println(string(data), err) // "file contents" // Write is not set, but with -stub it won't panic: n, err := mockedFS.Write("log.txt", []byte("entry")) fmt.Println(n, err) // 0 ``` -------------------------------- ### Mock Generic Interfaces (Go 1.18+) Source: https://context7.com/matryer/moq/llms.txt Moq fully supports generic interfaces. The generated mock struct includes the same type parameters as the source interface. Instantiate the mock with concrete types in your test. ```go // Source (store/store.go): // type GenericStore[T Key, S any] interface { // Get(ctx context.Context, id T) (S, error) // Create(ctx context.Context, id T, value S) error // } // // Generate: moq -out store_mock_test.go . GenericStore // Instantiate with concrete types in the test mockedStore := &GenericStore1Mock[MyKey, UserRecord]{ GetFunc: func(ctx context.Context, id MyKey) (UserRecord, error) { return UserRecord{Name: "Alice"}, nil }, CreateFunc: func(ctx context.Context, id MyKey, value UserRecord) error { return nil }, } ctx := context.Background() user, err := mockedStore.Get(ctx, MyKey("u-001")) fmt.Println(user.Name, err) // Alice getCalls := mockedStore.GetCalls() fmt.Println(getCalls[0].ID) // u-001 ``` -------------------------------- ### Generate Mock with Reset Helpers Source: https://context7.com/matryer/moq/llms.txt Generate a mock that includes Reset*Calls() helper methods. These methods allow you to clear the call history of the mock between test cases. ```bash moq -with-resets -out mocks_test.go . MyInterface ``` -------------------------------- ### Inspect Mocked Method Invocations with Calls() Source: https://context7.com/matryer/moq/llms.txt Access recorded invocations of a mocked method using the `Calls()` accessor. This returns a slice of structs, each representing a call with its arguments. ```go // PersonStore mock from the example package mockedStore := &PersonStoreMock{ GetFunc: func(ctx context.Context, id string) (*Person, error) { return &Person{ID: id, Name: "Alice"}, nil }, CreateFunc: func(ctx context.Context, person *Person, confirm bool) error { return nil }, } // Exercise the mock ctx := context.Background() _, _ = mockedStore.Get(ctx, "abc-123") _, _ = mockedStore.Get(ctx, "xyz-999") _ = mockedStore.Create(ctx, &Person{Name: "Bob"}, true) // Inspect Get calls getCalls := mockedStore.GetCalls() fmt.Println(len(getCalls)) // 2 fmt.Println(getCalls[0].ID) // "abc-123" fmt.Println(getCalls[1].ID) // "xyz-999" // Inspect Create calls createCalls := mockedStore.CreateCalls() fmt.Println(len(createCalls)) // 1 fmt.Println(createCalls[0].Person.Name) // "Bob" fmt.Println(createCalls[0].Confirm) // true ``` -------------------------------- ### Use Generated Mock in Go Tests Source: https://context7.com/matryer/moq/llms.txt Integrate generated mocks into your tests by assigning implementations to the mock's Func fields and asserting call details using the accessor methods. Ensure the mock is injected where the real interface is expected. ```go // Source interface (service/service.go): // //go:generate moq -out mock_test.go . EmailSender // type EmailSender interface { // Send(to, subject, body string) error // } package service_test import ( "testing" "service" ) func TestCompleteSignup(t *testing.T) { var capturedTo string mockedSender := &service.EmailSenderMock{ // Provide the implementation inline SendFunc: func(to, subject, body string) error { capturedTo = to return nil }, } // Inject the mock wherever the real EmailSender is expected err := service.CompleteSignUp("user@example.com", mockedSender) if err != nil { t.Fatalf("unexpected error: %v", err) } // Assert call count calls := mockedSender.SendCalls() if len(calls) != 1 { t.Errorf("expected Send called once, got %d", len(calls)) } // Assert argument values from recorded call if calls[0].To != "user@example.com" { t.Errorf("unexpected recipient: %s", calls[0].To) } if capturedTo != "user@example.com" { t.Errorf("closure did not capture recipient: %s", capturedTo) } } ``` -------------------------------- ### Generate Mock Skipping Interface Check Source: https://context7.com/matryer/moq/llms.txt Generate a mock while skipping the compile-time interface satisfaction check. This can help avoid import cycles in complex projects. ```bash moq -skip-ensure -out mocks_test.go . MyInterface ``` -------------------------------- ### Handle Variadic Parameters in Mocked Methods Source: https://context7.com/matryer/moq/llms.txt Variadic arguments are collected into a slice in the recorded call struct. The generated method signature correctly uses `...T`. ```go // Source interface: // type Echoer interface { // Echo(ss ...string) []string // } mockedEchoer := &EchoerMock{ EchoFunc: func(ss ...string) []string { return ss }, } result := mockedEchoer.Echo("hello", "world", "moq") fmt.Println(result) // [hello world moq] calls := mockedEchoer.EchoCalls() fmt.Println(calls[0].Ss) // [hello world moq] ``` -------------------------------- ### Reset Mock Call History with ResetCalls() / ResetCalls() Source: https://context7.com/matryer/moq/llms.txt Clear the recorded call history of mocks when generated with the `-with-resets` flag. Use `ResetCalls()` for specific methods or `ResetCalls()` to clear all history. ```go // Generate with: moq -with-resets -out mock_test.go . Notifier mockedNotifier := &NotifierMock{ NotifyFunc: func(msg string) error { return nil }, } // First sub-test phase mockedNotifier.Notify("hello") fmt.Println(len(mockedNotifier.NotifyCalls())) // 1 // Reset only the Notify method's call history mockedNotifier.ResetNotifyCalls() fmt.Println(len(mockedNotifier.NotifyCalls())) // 0 mockedNotifier.Notify("world") mockedNotifier.Notify("again") fmt.Println(len(mockedNotifier.NotifyCalls())) // 2 // Reset all methods at once mockedNotifier.ResetCalls() fmt.Println(len(mockedNotifier.NotifyCalls())) // 0 ``` -------------------------------- ### Generate Mock with Custom Alias Source: https://context7.com/matryer/moq/llms.txt Generate a mock for an interface and assign a custom alias to the generated mock struct. This is useful for avoiding naming conflicts or for clearer naming. ```bash moq -pkg different . MyInterface:MyMock ``` -------------------------------- ### Generate Mocks Outside Tested Package with -skip-ensure Source: https://context7.com/matryer/moq/llms.txt Use the `-skip-ensure` flag when generating mocks in a separate package to avoid circular import issues. This flag omits the compile-time interface satisfaction check. ```bash # Generate a mock for service.MyInterface into a sibling "mocks" package moq -pkg mocks -skip-ensure -out ./mocks/myinterface_mock.go ./service MyInterface ``` ```go // mocks/myinterface_mock.go (generated, no import cycle) package mocks // MyInterfaceMock is a mock implementation of service.MyInterface. type MyInterfaceMock struct { DoSomethingFunc func(id int) error // ... } // In the test file: // import "myrepo/mocks" // mock := &mocks.MyInterfaceMock{ DoSomethingFunc: ... } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.