### Install minimock CLI Source: https://github.com/gojuno/minimock/blob/master/_autodocs/README.md Installs the minimock command-line tool. Ensure your Go environment is set up correctly. ```bash go install github.com/gojuno/minimock/v3/cmd/minimock@latest ``` -------------------------------- ### Simple Mock Setup in Go Source: https://github.com/gojuno/minimock/blob/master/_autodocs/README.md Demonstrates the basic setup for creating and using a mock object. Ensure a minimock controller is initialized with the testing.T instance. ```go mc := minimock.NewController(t) mock := NewReaderMock(mc) mock.ReadMock.Return(5, nil) // Use the mock n, err := mock.Read(buf) ``` -------------------------------- ### Setup Mock with Builder and Expect/Return Source: https://github.com/gojuno/minimock/blob/master/README.md Use the builder pattern with Expect/Return for straightforward mock method setup. This is convenient for mocking multiple methods on an interface. ```go mc := minimock.NewController(t) formatterMock := NewFormatterMock(mc).FormatMock.Expect("hello %s!", "world").Return("hello world!") ``` -------------------------------- ### Install minimock CLI Source: https://github.com/gojuno/minimock/blob/master/README.md Install the minimock command-line tool using Go modules. This command downloads the latest binary for use in your projects. ```bash go install github.com/gojuno/minimock/v3/cmd/minimock@latest ``` -------------------------------- ### Usage Example: Creating a Controller and Registering Mocks Source: https://github.com/gojuno/minimock/blob/master/_autodocs/api-reference/mock-controller-interface.md Example demonstrating how to create a MockController and use it with generated mocks. ```APIDOC ## Usage Examples ### Creating a Controller and Registering Mocks ```go package main import ( "testing" "github.com/gojuno/minimock/v3" ) func TestMyFunction(t *testing.T) { // Create a MockController mc := minimock.NewController(t) // Pass it to mock constructors to auto-register formatterMock := NewFormatterMock(mc) formatterMock.FormatMock.Expect("hello").Return("world") // Register is called automatically in NewFormatterMock readerMock := NewReaderMock(mc) readerMock.ReadMock.Return(5, nil) // Test code here... // All mocks are automatically verified when test ends } ``` ``` -------------------------------- ### Example Interface Definition Source: https://github.com/gojuno/minimock/blob/master/_autodocs/generated-mock-structure.md An example of a Go interface that can be mocked by minimock. This interface defines a single method 'Format'. ```go type Formatter interface { Format(string, ...interface{}) string } ``` -------------------------------- ### FormatterMock Implementation Example Source: https://github.com/gojuno/minimock/blob/master/_autodocs/generated-mock-structure.md This example shows how a mock implements an original interface by delegating to function fields and handling expectations and call counts. ```go func (m *FormatterMock) Format(p string, p1 ...interface{}) string { defer atomic.AddUint64(&m.FormatCounter, 1) if m.FormatMock.mockExpectations != nil { testify_assert.Equal(m.t, *m.FormatMock.mockExpectations, FormatterMockFormatParams{p, p1}, "Formatter.Format got unexpected parameters") if m.FormatFunc == nil { m.t.Fatal("No results are set for the FormatterMock.Format") return } } if m.FormatFunc == nil { m.t.Fatal("Unexpected call to FormatterMock.Format") return } return m.FormatFunc(p, p1...) } ``` -------------------------------- ### Mock Usage Example Source: https://github.com/gojuno/minimock/blob/master/_autodocs/generated-mock-structure.md Demonstrates how to create and use a mock instance generated by minimock. It shows creating a controller and then instantiating a mock, which is automatically registered. ```go mc := minimock.NewController(t) mock := NewFormatterMock(mc) // Auto-registered ``` -------------------------------- ### Explicit Setup/Teardown with Minimock Source: https://github.com/gojuno/minimock/blob/master/_autodocs/api-reference/integration-with-testing.md Shows how to manage mock setup and teardown explicitly, even though minimock uses controller cleanup registration. This pattern is useful for complex test scenarios. ```go func TestWithExplicitCleanup(t *testing.T) { mc := minimock.NewController(t) setupMocks := func() *FormatterMock { mock := NewFormatterMock(mc) mock.FormatMock.Return("result") return mock } cleanup := func(mock *FormatterMock) { mock.MinimockFinish() // Explicit verification } mock := setupMocks() defer cleanup(mock) result := mock.Format("test") // ... } ``` -------------------------------- ### Minimock Development Workflow: Initial Generation and Regeneration Source: https://github.com/gojuno/minimock/blob/master/_autodocs/configuration.md This example outlines the development workflow for using minimock. It covers initial mock generation and subsequent regeneration after interface modifications, utilizing `go generate`. ```bash # Initial generation minimock -i MyInterface -o ./test_mocks ``` ```bash # Modify interface... # Regenerate go generate ./test_mocks # Or regenerate all go generate ./... ``` -------------------------------- ### Basic Tester Implementation with *testing.T Source: https://github.com/gojuno/minimock/blob/master/_autodocs/api-reference/integration-with-testing.md Demonstrates how to use `*testing.T` directly with minimock to create a controller and mock objects. The `*testing.T` type implements the `Tester` interface, simplifying mock setup. ```go package myapp import ( "testing" "github.com/gojuno/minimock/v3" ) func TestMyFunction(t *testing.T) { // *testing.T implements Tester mc := minimock.NewController(t) // All minimock types work directly with *testing.T myMock := NewMyInterfaceMock(mc) myMock.SomeMethodMock.Return("result") } ``` -------------------------------- ### Generated Mock Constructor Example Source: https://github.com/gojuno/minimock/blob/master/_autodocs/generated-mock-structure.md An example of a generated constructor function for the 'FormatterMock'. It initializes the mock, registers it with the controller if applicable, and sets up the associated mock builder. ```go func NewFormatterMock(t minimock.Tester) *FormatterMock { m := &FormatterMock{t: t} if controller, ok := t.(minimock.MockController); ok { controller.RegisterMocker(m) } m.FormatMock = mFormatterMockFormat{mock: m} return m } ``` -------------------------------- ### Custom MockController Implementation Source: https://github.com/gojuno/minimock/blob/master/_autodocs/api-reference/mock-controller-interface.md Provides an example of implementing a custom MockController. This is useful when you need to extend or modify the default controller behavior. ```go type CustomController struct { t *testing.T mockers []minimock.Mocker sync.Mutex } func (c *CustomController) RegisterMocker(m minimock.Mocker) { c.Lock() defer c.Unlock() c.mockers = append(c.mockers, m) } func (c *CustomController) Fatal(args ...interface{}) { c.t.Fatal(args...) } func (c *CustomController) Fatalf(format string, args ...interface{}) { c.t.Fatalf(format, args...) } // Implement other Tester methods... func TestWithCustomController(t *testing.T) { cc := &CustomController{t: t} myMock := NewMyInterfaceMock(cc) // Mock is automatically registered } ``` -------------------------------- ### Custom Tester Implementation Example Source: https://github.com/gojuno/minimock/blob/master/_autodocs/api-reference/tester-interface.md Demonstrates how to implement the Tester interface for custom wrapper types. This example shows a CustomTester that delegates calls to a standard *testing.T instance, allowing minimock-generated mocks to be used with custom test runners. ```go package main import "testing" // *testing.T implements the Tester interface var _ minimock.Tester = (*testing.T)(nil) // CustomTester shows how to implement Tester for wrapper types type CustomTester struct { t *testing.T } func (ct *CustomTester) Fatal(args ...interface{}) { ct.t.Fatal(args...) } func (ct *CustomTester) Fatalf(format string, args ...interface{}) { ct.t.Fatalf(format, args...) } func (ct *CustomTester) Error(args ...interface{}) { ct.t.Error(args...) } func (ct *CustomTester) Errorf(format string, args ...interface{}) { ct.t.Errorf(format, args...) } func (ct *CustomTester) FailNow() { ct.t.FailNow() } func (ct *CustomTester) Cleanup(f func()) { ct.t.Cleanup(f) } func (ct *CustomTester) Helper() { ct.t.Helper() } func TestWithCustomTester(t *testing.T) { ct := &CustomTester{t: t} mc := minimock.NewController(ct) // Use controller with custom tester myMock := NewMyInterfaceMock(mc) myMock.SomeMethodMock.Return("result") } ``` -------------------------------- ### Table-Driven Tests with Minimock Source: https://github.com/gojuno/minimock/blob/master/_autodocs/api-reference/integration-with-testing.md Shows how to use minimock within Go's table-driven test pattern. Each test case defines its own setup function, and a new controller is created for each subtest, ensuring isolated mock verification. ```go func TestFormatterWithTableDriven(t *testing.T) { tests := []struct { name string input string expected string setup func(*FormatterMock) }{ { name: "simple format", input: "hello %s", expected: "hello world", setup: func(m *FormatterMock) { m.FormatMock.Expect("hello %s").Return("hello world") }, }, { name: "complex format", input: "%d items", expected: "5 items", setup: func(m *FormatterMock) { m.FormatMock.Expect("%d items").Return("5 items") }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { mc := minimock.NewController(t) mock := NewFormatterMock(mc) tt.setup(mock) result := mock.Format(tt.input) if result != tt.expected { t.Errorf("got %q, want %q", result, tt.expected) } }) } } ``` -------------------------------- ### Generated Mock Struct Example Source: https://github.com/gojuno/minimock/blob/master/_autodocs/generated-mock-structure.md Illustrates the concrete structure of a mock generated for the 'Formatter' interface. It includes specific fields for the 'Format' method. ```go type FormatterMock struct { t minimock.Tester FormatFunc func(p string, p1 ...interface{}) (r string) FormatCounter uint64 FormatMock mFormatterMockFormat } ``` -------------------------------- ### Define Go Interface Source: https://github.com/gojuno/minimock/blob/master/README.md Example of a Go interface declaration. Minimock generates mocks based on these interface definitions. ```go type Formatter interface { Format(string, ...interface{}) string } ``` -------------------------------- ### Conditional Mock Call Setup in Go Source: https://github.com/gojuno/minimock/blob/master/_autodocs/README.md Explains how to configure mock method calls for optional, required, or specific counts. Use `.Optional()` for non-critical calls and `.Times(n)` for exact call counts. ```go // Optional - doesn't fail if not called mock.MethodMock.Optional().Return("result") // Required - fails if not called mock.MethodMock.Return("result") // Specific count expected mock.MethodMock.Times(3).Return("result") ``` -------------------------------- ### Generated MinimockFinish Implementation Source: https://github.com/gojuno/minimock/blob/master/_autodocs/api-reference/mocker-interface.md Example of how minimock generates the MinimockFinish method for a specific mock structure, checking call counters. ```go func (m *FormatterMock) MinimockFinish() { if m.FormatFunc != nil && atomic.LoadUint64(&m.FormatCounter) == 0 { m.t.Fatal("Expected call to FormatterMock.Format") } } ``` -------------------------------- ### Generated MinimockWait Implementation Source: https://github.com/gojuno/minimock/blob/master/_autodocs/api-reference/mocker-interface.md Example of minimock's generated MinimockWait method, which polls mock call counters until they are met or a timeout occurs. ```go func (m *FormatterMock) MinimockWait(timeout time.Duration) { timeoutCh := time.After(timeout) for { ok := true ok = ok && (m.FormatFunc == nil || atomic.LoadUint64(&m.FormatCounter) > 0) if ok { return } select { case <-timeoutCh: if m.FormatFunc != nil && atomic.LoadUint64(&m.FormatCounter) == 0 { m.t.Error("Expected call to FormatterMock.Format") } m.t.Fatalf("Some mocks were not called on time: %s", timeout) return default: time.Sleep(time.Millisecond) } } } ``` -------------------------------- ### CallerInfo: Get caller's file path and line number Source: https://github.com/gojuno/minimock/blob/master/_autodocs/api-reference/utility-functions.md Returns the file path and line number of a caller in the call stack. Use the 'skip' parameter to control how many frames to go up. Useful for debugging and error reporting. ```go package main import ( "fmt" "github.com/gojuno/minimock/v3" ) func exampleFunction() { // Get caller info info := minimock.CallerInfo(0) // Immediate caller fmt.Println(info) // Output: /path/to/main.go:10 } func testHelper() { // Skip the current function and get the caller of testHelper info := minimock.CallerInfo(1) fmt.Println(info) } func main() { exampleFunction() testHelper() // CallerInfo(1) inside testHelper will show main.go:line } ``` ```go // Example of how it might be used in test utilities func assertMockCalled(t *testing.T, mock minimock.Mocker) { callerLocation := minimock.CallerInfo(1) t.Logf("Mock verification requested from %s", callerLocation) } ``` -------------------------------- ### Using a Fixture Pattern with Minimock Source: https://github.com/gojuno/minimock/blob/master/_autodocs/api-reference/integration-with-testing.md Illustrates the fixture pattern for setting up mocks and test data. This approach centralizes mock creation and initialization for cleaner tests. ```go func newTestFixture(t *testing.T) *testFixture { mc := minimock.NewController(t) return &testFixture{ mc: mc, format: NewFormatterMock(mc), reader: NewReaderMock(mc), } } type testFixture struct { mc *minimock.Controller format *FormatterMock reader *ReaderMock } func TestWithFixture(t *testing.T) { f := newTestFixture(t) f.format.FormatMock.Return("result") // Use fixture... } ``` -------------------------------- ### Benchmark Integration with minimock Source: https://github.com/gojuno/minimock/blob/master/_autodocs/api-reference/integration-with-testing.md Demonstrates how to use minimock within Go benchmarks. Note that mocks typically add overhead and are often excluded for accurate performance measurements. ```go func BenchmarkWithMock(b *testing.B) { // Create a dummy Tester that doesn't fail // since benchmarks don't use *testing.T's failure methods var mockT testing.T mc := minimock.NewController(&mockT) mock := NewFormatterMock(mc) mock.FormatMock.Return("result") b.ResetTimer() for i := 0; i < b.N; i++ { _ = mock.Format("input") } } ``` -------------------------------- ### Basic Usage with MockController Source: https://github.com/gojuno/minimock/blob/master/_autodocs/api-reference/mock-controller-interface.md Demonstrates how to create a MockController and pass it to mock constructors. Mocks are automatically registered and verified upon test completion. ```go package main import ( "testing" "github.com/gojuno/minimock/v3" ) func TestMyFunction(t *testing.T) { // Create a MockController mc := minimock.NewController(t) // Pass it to mock constructors to auto-register formatterMock := NewFormatterMock(mc) formatterMock.FormatMock.Expect("hello").Return("world") // Register is called automatically in NewFormatterMock readerMock := NewReaderMock(mc) readerMock.ReadMock.Return(5, nil) // Test code here... // All mocks are automatically verified when test ends } ``` -------------------------------- ### Go: Timeout Waiting for Mocks Example Source: https://github.com/gojuno/minimock/blob/master/_autodocs/errors.md Illustrates a test where Controller.Wait() times out because a goroutine is too slow to call the expected mock method. This is common in concurrent tests. ```go func TestConcurrentWithTimeout(t *testing.T) { mc := minimock.NewController(t) mock := NewFormatterMock(mc) mock.FormatMock.Return("result") go func() { time.Sleep(2 * time.Second) // Too slow mock.Format("input") }() defer mc.Wait(time.Second) // Timeout before goroutine completes } ``` -------------------------------- ### Setting Up Mock Expectations Source: https://github.com/gojuno/minimock/blob/master/_autodocs/api-reference/integration-with-testing.md Set up mock expectations before calling the mock methods to ensure predictable behavior and easier debugging. Avoid setting expectations after the call, as it can lead to unexpected failures. ```go // Good mock := NewFormatterMock(mc) mock.FormatMock.Expect("hello").Return("world") result := mock.Format("hello") ``` ```go // Avoid - hard to debug mock := NewFormatterMock(mc) result := mock.Format("hello") // Unexpected call mock.FormatMock.Expect("hello").Return("world") ``` -------------------------------- ### Define AnyContext sentinel value Source: https://github.com/gojuno/minimock/blob/master/_autodocs/types.md A sentinel value used in mock expectations to match any context.Context. This is useful for simplifying mock setup when the context value is not critical. ```go var AnyContext = anyContext{} ``` -------------------------------- ### Using Multiple Mocks in Go Source: https://github.com/gojuno/minimock/blob/master/_autodocs/README.md Shows how to set up and configure multiple mock objects within a single test. All mocks are verified together at the end of the test. ```go mc := minimock.NewController(t) formatter := NewFormatterMock(mc) reader := NewReaderMock(mc) writer := NewWriterMock(mc) formatter.FormatMock.Return("result") reader.ReadMock.Return(5, nil) writer.WriteMock.Return(10, nil) // All mocks verified together at test end ``` -------------------------------- ### Get Method Call Count with Minimock Source: https://github.com/gojuno/minimock/blob/master/_autodocs/generated-mock-structure.md Use the counter method to retrieve the number of times a specific mocked method has been called. It is initially 0 and increments with each call. ```go func (m *Mock) MinimockCounter() uint64 ``` ```go mock := NewFormatterMock(mc) mock.FormatMock.Return("result") count := mock.FormatMinimockCounter() // 0 initially mock.Format("test") count = mock.FormatMinimockCounter() // 1 after call ``` -------------------------------- ### Display Version Information Source: https://github.com/gojuno/minimock/blob/master/_autodocs/api-reference/cli-command.md Use the -version flag to display the current version of the minimock CLI. ```bash minimock -version ``` -------------------------------- ### Create Minimock Controller Source: https://github.com/gojuno/minimock/blob/master/_autodocs/README.md Instantiate a new minimock controller, passing the testing.T object. Mocks are automatically registered with this controller. It's recommended to defer `mc.Finish()` for cleanup, though it happens automatically. ```go mc := minimock.NewController(t) // Create controller mock := NewMyMock(mc) // Mocks auto-register defer mc.Finish() // Optional - happens automatically ``` -------------------------------- ### Go: Mock Not Called Error Example Source: https://github.com/gojuno/minimock/blob/master/_autodocs/errors.md Demonstrates a scenario where a mock's expectation is set but never called, leading to a test failure. Use this when your test logic does not invoke a mocked method. ```go func TestWithUnusedMock(t *testing.T) { mc := minimock.NewController(t) mock := NewFormatterMock(mc) mock.FormatMock.Return("result") // Never called - test fails // Error: Expected call to FormatterMock.Format } ``` -------------------------------- ### Use minimock in Go tests Source: https://github.com/gojuno/minimock/blob/master/_autodocs/README.md Demonstrates basic usage of minimock within a Go test function. It shows how to create a mock controller, instantiate a mock, set expectations, and call a mocked method. ```go import "github.com/gojuno/minimock/v3" func TestMyFunction(t *testing.T) { mc := minimock.NewController(t) myMock := NewMyInterfaceMock(mc) myMock.SomeMethodMock.Expect(42).Return("result") // Test code here... result := myMock.SomeMethod(42) } ``` -------------------------------- ### Configure Mock with Builder Pattern Source: https://github.com/gojuno/minimock/blob/master/_autodocs/README.md Use the builder pattern for fluent mock configuration. Chain methods like `Expect`, `Inspect`, and `Return` to define mock behavior. ```go mock.MethodMock. Expect(arg1, arg2). Inspect(func(a, b int) { // Optional parameter inspection }). Return(result) ``` -------------------------------- ### Typical Go Generate Usage for Minimock Source: https://github.com/gojuno/minimock/blob/master/_autodocs/configuration.md This demonstrates the common pattern of using the `//go:generate minimock` directive within an interface definition file. Running `go generate ./...` will then regenerate the mock. ```go package main // Interface definition type Formatter interface { Format(string, ...interface{}) string } //go:generate minimock -i Formatter -o formatter_mock_test.go ``` -------------------------------- ### Mocking io.ReadCloser Interface Source: https://github.com/gojuno/minimock/blob/master/README.md Demonstrates mocking the io.ReadCloser interface, which has Read and Close methods, using a concise one-liner with Expect/Return. ```go type ReadCloser interface { Read(p []byte) (n int, err error) Close() error } ``` ```go mc := minimock.NewController(t) readCloserMock := NewReadCloserMock(mc).ReadMock.Expect([]byte(1,2,3)).Return(3, nil).CloseMock.Return(nil) ``` -------------------------------- ### Generate Mock with Full Import Path and Output Directory Source: https://github.com/gojuno/minimock/blob/master/README.md Generate a mock for an interface using its full import path and specify an output directory. The generated mock file will be placed in the specified directory. ```bash $ minimock -i github.com/gojuno/minimock/tests.Formatter -o ./tests/ ``` -------------------------------- ### Project File Structure Source: https://github.com/gojuno/minimock/blob/master/_autodocs/MANIFEST.md This tree displays the generated documentation file structure within the /workspace/home/output/ directory. ```tree output/ ├── README.md ├── types.md ├── configuration.md ├── errors.md ├── generated-mock-structure.md ├── MANIFEST.md (this file) └── api-reference/ ├── controller.md ├── tester-interface.md ├── mocker-interface.md ├── mock-controller-interface.md ├── equality-and-comparison.md ├── utility-functions.md ├── cli-command.md └── integration-with-testing.md ``` -------------------------------- ### Display Help Message Source: https://github.com/gojuno/minimock/blob/master/_autodocs/api-reference/cli-command.md Use the -h flag to display the help message for the minimock CLI, listing all available commands and options. ```bash minimock -h ``` -------------------------------- ### Regenerate Mocks with go generate (go run) Source: https://github.com/gojuno/minimock/blob/master/_autodocs/api-reference/cli-command.md Demonstrates how to regenerate mocks using 'go run' when the '-gr' flag was used during initial generation. This ensures consistency with the go.mod file. ```bash minimock -gr -i Formatter go generate ./... ``` -------------------------------- ### Production-Style Minimock Configuration Source: https://github.com/gojuno/minimock/blob/master/_autodocs/configuration.md Configure minimock to mock specific interfaces, write to a dedicated output directory, use custom package and mock names, and apply a custom file suffix for better organization. ```bash minimock \ -i "github.com/company/pkg.Reader,github.com/company/pkg.Writer" \ -o ./internal/mocks \ -p mocks \ -n "ReaderMock,WriterMock" \ -s "_test_mock.go" ``` -------------------------------- ### Using Minimock with Testify Assertions Source: https://github.com/gojuno/minimock/blob/master/_autodocs/api-reference/integration-with-testing.md Demonstrates how to use minimock with the stretchr/testify assertion library. The minimock controller works with any assertion library that uses the standard testing.T interface. ```go import ( t"testing" "github.com/stretchr/testify/assert" "github.com/gojuno/minimock/v3" ) func TestWithTestify(t *testing.T) { mc := minimock.NewController(t) mock := NewFormatterMock(mc) mock.FormatMock.Expect("input").Return("output") result := mock.Format("input") assert.Equal(t, "output", result) assert.Equal(t, uint64(1), mock.FormatMinimockCounter()) } ``` -------------------------------- ### Minimock Project File Organization Source: https://github.com/gojuno/minimock/blob/master/_autodocs/INDEX.md This snippet shows the directory structure for the minimock project's documentation files. It includes the main entry points and categorized API references. ```text /workspace/home/output/ ├── README.md # Start here ├── MANIFEST.md # Detailed coverage ├── INDEX.md # This file ├── types.md # All type definitions ├── configuration.md # CLI configuration ├── errors.md # Error reference ├── generated-mock-structure.md # Mock internals └── api-reference/ ├── controller.md ├── tester-interface.md ├── mocker-interface.md ├── mock-controller-interface.md ├── equality-and-comparison.md ├── utility-functions.md ├── cli-command.md └── integration-with-testing.md ``` -------------------------------- ### Mocking with When/Then Helpers Source: https://github.com/gojuno/minimock/blob/master/README.md Utilize When/Then helpers to define mock behavior based on specific input arguments. This allows for setting up multiple distinct return values for the same method based on different inputs. ```go mc := minimock.NewController(t) formatterMock := NewFormatterMock(mc) formatterMock.FormatMock.When("Hello %s!", "world").Then("Hello world!") formatterMock.FormatMock.When("Hi %s!", "there").Then("Hi there!") ``` ```go formatterMock = NewFormatterMock(mc).FormatMock.When("Hello %s!", "world").Then("Hello world!").FormatMock.When("Hi %s!", "there").Then("Hi there!") ``` -------------------------------- ### Expect Method for Setting Parameters Source: https://github.com/gojuno/minimock/blob/master/_autodocs/generated-mock-structure.md Use the Expect method to define the parameters that a mock method call should receive. This is the first step in setting up a mock expectation. ```go func (m *mMock) Expect(...) *mMock ``` ```go mock.FormatMock.Expect("hello %s", "world") ``` -------------------------------- ### Basic minimock Command Source: https://github.com/gojuno/minimock/blob/master/_autodocs/api-reference/cli-command.md The fundamental command to generate mock implementations. It takes options to specify interfaces and output locations. ```bash minimock [options] ``` -------------------------------- ### Generate All io Package Interfaces Source: https://github.com/gojuno/minimock/blob/master/_autodocs/api-reference/cli-command.md Generate mocks for all interfaces within a specific Go package, such as the 'io' package. Specify the package using a wildcard and an output directory. ```bash minimock -i "io.*" -o ./io_mocks ``` -------------------------------- ### When/Then for Parameter-Response Mapping Source: https://github.com/gojuno/minimock/blob/master/_autodocs/generated-mock-structure.md The When/Then methods allow setting up multiple parameter-to-result mappings in a dictionary-like pattern. This is useful for defining varied responses based on specific inputs. ```go func (m *mMock) When(...) *whenFormatterMockFormat func (w *whenFormatterMockFormat) Then(...) *FormatterMock ``` ```go mock.FormatMock. When("hello %s", "world").Then("greeting"). When("goodbye %s", "friend").Then("farewell") ``` -------------------------------- ### Automatic Cleanup Registration Source: https://github.com/gojuno/minimock/blob/master/_autodocs/api-reference/integration-with-testing.md Illustrates the internal `NewController` function, showing how it automatically registers a cleanup function using `t.Cleanup(c.Finish)`. This eliminates the need for manual `defer mc.Finish()` calls. ```go func NewController(t Tester) *Controller { c := Controller{Tester: newSafeTester(t)} t.Cleanup(c.Finish) // Automatically registered return &c } ``` -------------------------------- ### Minimock with Go Module Version Control Source: https://github.com/gojuno/minimock/blob/master/_autodocs/configuration.md Integrate minimock with Go modules for version-controlled mock generation. This ensures that mock regeneration uses the current Go module version automatically. ```bash minimock -gr -i "io.*" -o ./io_mocks ``` ```bash go generate ./... # Later runs: go run github.com/gojuno/minimock/v3/cmd/minimock ``` -------------------------------- ### Generate Mocks for All Interfaces in Current Package Source: https://github.com/gojuno/minimock/blob/master/_autodocs/api-reference/cli-command.md Use this command to generate mocks for all interfaces found in the current directory. Mocks are placed in the same package. ```bash minimock ``` -------------------------------- ### Concurrent Code Testing with MinimockWait Source: https://github.com/gojuno/minimock/blob/master/_autodocs/api-reference/mocker-interface.md Illustrates testing concurrent code by using MinimockWait() on an individual mock to ensure expected calls are made within a timeout. ```go func TestConcurrentCall(t *testing.T) { mc := minimock.NewController(t) myMock := NewMyInterfaceMock(mc) myMock.SomeMethodMock.Return("value") // Start goroutine that will call the mock go myMock.SomeMethod() // Wait for the mock to be called myMock.MinimockWait(time.Second) } ``` -------------------------------- ### Explicit Verification with MinimockFinish Source: https://github.com/gojuno/minimock/blob/master/_autodocs/api-reference/mocker-interface.md Shows how to explicitly call MinimockFinish() on a mock to verify expectations before the test completes. ```go func TestWithExplicitFinish(t *testing.T) { mc := minimock.NewController(t) myMock := NewMyInterfaceMock(mc) myMock.SomeMethodMock.Return("value") // Do something with the mock result := myMock.SomeMethod() // Explicitly verify expectations myMock.MinimockFinish() } ``` -------------------------------- ### Mocking with AnyContext Source: https://github.com/gojuno/minimock/blob/master/README.md Use minimock.AnyContext to ignore the exact value of the context argument when setting up mocks. This is helpful when the context's state at call time is not relevant to the test. ```go mc := minimock.NewController(t) senderMock := NewSenderMock(mc). SendMock. When(minimock.AnyContext, "message1").Then(nil). When(minimock.AnyContext, "message2").Then(errors.New("invalid message")) ``` ```go mc := minimock.NewController(t) senderMock := NewSenderMock(mc). SendMock.Expect(minimock.AnyContext, "message").Return(nil) ``` -------------------------------- ### Minimock CLI Usage Source: https://github.com/gojuno/minimock/blob/master/README.md Command-line interface options for the minimock tool. Use flags to specify interfaces, output directories, and file naming conventions. ```bash minimock [-i source.interface] [-o output/dir/or/file.go] [-g] -g don't put go:generate instruction into the generated code -h show this help message -i string comma-separated names of the interfaces to mock, i.e fmt.Stringer,io.Reader use io.* notation to generate mocks for all interfaces in the "io" package (default "*") -o string comma-separated destination file names or packages to put the generated mocks in, by default the generated mock is placed in the source package directory -p string comma-separated package names, by default the generated package names are taken from the destination directory names -pr string mock file prefix -s string mock file suffix (default "_mock_test.go") -gr changes go:generate line from "//go:generate minimock args..." to "//go:generate go run github.com/gojuno/minimock/v3/cmd/minimock", useful while controlling minimock version with go mod ``` -------------------------------- ### Create New Controller Source: https://github.com/gojuno/minimock/blob/master/_autodocs/api-reference/controller.md Creates a new Controller instance, wrapping a Tester (typically *testing.T). It automatically registers a Cleanup function to call Finish() when the test completes. ```go package main import ( "testing" "github.com/gojuno/minimock/v3" ) func TestMyFunction(t *testing.T) { mc := minimock.NewController(t) // Create mocks with the controller myMock := NewMyInterfaceMock(mc) myMock.SomeMethodMock.Return("result") // All mocks are automatically verified when test completes } ``` -------------------------------- ### Generate mocks for multiple interfaces with go:generate Source: https://github.com/gojuno/minimock/blob/master/_autodocs/README.md Generates mocks for multiple interfaces using a comma-separated list. This is typically used with Go's generate directive. ```bash minimock -i "fmt.Stringer,io.Reader" -o ./test_mocks ``` -------------------------------- ### Enable Go Run Mode for Go Generate with -gr Flag Source: https://github.com/gojuno/minimock/blob/master/_autodocs/api-reference/cli-command.md Use the -gr flag to change the '//go:generate' instruction to use 'go run' instead of directly calling minimock. This allows version control via go.mod. ```bash minimock -gr -i Formatter ``` -------------------------------- ### Usage of Equal and Diff in Generated Mocks Source: https://github.com/gojuno/minimock/blob/master/_autodocs/api-reference/equality-and-comparison.md Generated mocks utilize `Equal()` to verify actual parameters against expected ones and `Diff()` to create detailed error messages when parameters do not match. This pattern ensures robust testing of mock interactions. ```go func (m *FormatterMock) Format(p string, p1 ...interface{}) string { defer atomic.AddUint64(&m.FormatCounter, 1) if m.FormatMock.mockExpectations != nil { // Use Equal to check if actual params match expected if !minimock.Equal(*m.FormatMock.mockExpectations, FormatterMockFormatParams{p, p1}) { // Use Diff to generate helpful error message diff := minimock.Diff(*m.FormatMock.mockExpectations, FormatterMockFormatParams{p, p1}) m.t.Errorf("Formatter.Format got unexpected parameters%s", diff) } } if m.FormatFunc == nil { m.t.Fatal("No results are set for the FormatterMock.Format") } return m.FormatFunc(p, p1...) } ``` -------------------------------- ### Go Generate Directive for Mock Creation Source: https://github.com/gojuno/minimock/blob/master/_autodocs/configuration.md Use this directive in your Go source files to automatically generate mock implementations for interfaces. Specify the interface to mock and the output file name. ```go //go:generate minimock -i Formatter -o formatter_mock_test.go package main // Mock code generated here ``` -------------------------------- ### Automatic Verification with Controller Source: https://github.com/gojuno/minimock/blob/master/_autodocs/api-reference/mocker-interface.md Demonstrates how minimock automatically registers mocks with a Controller and calls MinimockFinish() during test cleanup. ```go func TestSomething(t *testing.T) { mc := minimock.NewController(t) // Any mocks created with mc are registered myMock := NewMyInterfaceMock(mc) myMock.SomeMethodMock.Return("value") // MinimockFinish() is called automatically when test completes // Test fails if SomeMethod() was never called } ``` -------------------------------- ### Generate Mock with Custom File Naming Source: https://github.com/gojuno/minimock/blob/master/_autodocs/api-reference/cli-command.md Customize the naming of generated mock files by specifying a prefix and a suffix. This allows for more organized mock file management. ```bash minimock -i Formatter -pr "generated_" -s ".mock.go" ``` -------------------------------- ### Inspecting Mock Call Parameters in Go Source: https://github.com/gojuno/minimock/blob/master/_autodocs/README.md Demonstrates how to inspect arguments passed to a mocked method using the `.Inspect()` function. This allows for custom validation of call arguments. ```go mock.MethodMock.Inspect(func(arg int) { if arg < 0 { mc.Error("expected positive argument") } }).Return("result") ``` -------------------------------- ### Mock Constructor Signature Source: https://github.com/gojuno/minimock/blob/master/_autodocs/generated-mock-structure.md Shows the signature for the constructor function generated by minimock for creating new mock instances. It takes a minimock.Tester as an argument. ```go func NewMock(t minimock.Tester) *Mock ``` -------------------------------- ### Specify Custom Package Name Source: https://github.com/gojuno/minimock/blob/master/_autodocs/configuration.md Use the -p flag to set a custom package name for the generated mock files, overriding the default behavior of using the directory name. ```bash minimock -p testpkg ``` ```bash minimock -o ./mocks -p mocks ``` -------------------------------- ### Generate Mock for Specific Interface Source: https://github.com/gojuno/minimock/blob/master/README.md Generate a mock for the 'Formatter' interface within the current directory. This command assumes you are in the package directory containing the interface. ```bash $ cd ~/go/src/github.com/gojuno/minimock/tests $ minimock -i Formatter ``` -------------------------------- ### Select Interfaces for Mock Generation Source: https://github.com/gojuno/minimock/blob/master/_autodocs/configuration.md Use the -i flag to specify which interfaces should have mocks generated. Supports single interfaces, comma-separated lists, or package-qualified names. ```bash minimock -i "fmt.Stringer,io.Reader" ``` -------------------------------- ### Generate mock for a single interface Source: https://github.com/gojuno/minimock/blob/master/_autodocs/README.md Generates a mock for a specified interface and outputs it to a given directory. Use this for single interface mock generation. ```bash minimock -i MyInterface -o ./mocks ``` -------------------------------- ### Centralized Verification with Controller Source: https://github.com/gojuno/minimock/blob/master/_autodocs/api-reference/integration-with-testing.md Use a single minimock controller to manage and verify multiple mocks in your tests. This approach centralizes mock verification, making tests cleaner and easier to debug. ```go // Good - centralized verification func TestWithMultipleMocks(t *testing.T) { mc := minimock.NewController(t) formatterMock := NewFormatterMock(mc) readerMock := NewReaderMock(mc) writerMock := NewWriterMock(mc) // All mocks verified together } ``` -------------------------------- ### Ensuring Mocks Are Used Source: https://github.com/gojuno/minimock/blob/master/README.md Utilize minimock.NewController and mc.Wait to ensure all defined mocks and expectations are actually used during the test. This helps identify dead code or unused dependencies. ```go func TestSomething(t *testing.T) { // it will mark this example test as failed because there are no calls // to formatterMock.Format() and readCloserMock.Read() below mc := minimock.NewController(t) formatterMock := NewFormatterMock(mc) formatterMock.FormatMock.Return("minimock") readCloserMock := NewReadCloserMock(mc) readCloserMock.ReadMock.Return(5, nil) } ``` -------------------------------- ### Generate Multiple Mocks with Custom Names Source: https://github.com/gojuno/minimock/blob/master/_autodocs/api-reference/cli-command.md Generate mocks for multiple interfaces and assign custom names to them. Specify the interfaces and their corresponding custom names, along with the output directory. ```bash minimock -i "fmt.Stringer,io.Reader" -n "StringerTest,ReaderTest" -o ./mocks ``` -------------------------------- ### Generate go:generate Instruction with Go Run Mode Source: https://github.com/gojuno/minimock/blob/master/_autodocs/configuration.md When -gr is set, the generated go:generate instruction uses 'go run' to specify the minimock binary. ```go //go:generate go run github.com/gojuno/minimock/v3/cmd/minimock [args] ``` -------------------------------- ### Regenerate Mocks with go generate Source: https://github.com/gojuno/minimock/blob/master/_autodocs/api-reference/cli-command.md After initial mock generation, use 'go generate' to regenerate mocks. This is particularly useful for version control workflows. ```bash go generate ./... ``` -------------------------------- ### Subtests with Independent Mock Verification Source: https://github.com/gojuno/minimock/blob/master/_autodocs/api-reference/integration-with-testing.md Employ `t.Run()` for subtests, ensuring separate mock verification per subtest by creating a new `Controller` for each. ```go func TestWithSubtests(t *testing.T) { mc := minimock.NewController(t) t.Run("subtest1", func(t *testing.T) { mc := minimock.NewController(t) mock := NewFormatterMock(mc) mock.FormatMock.Return("result1") // Use mock... }) t.Run("subtest2", func(t *testing.T) { mc := minimock.NewController(t) mock := NewFormatterMock(mc) mock.FormatMock.Return("result2") // Use mock... }) } ``` -------------------------------- ### Manually Finish Controller Verification Source: https://github.com/gojuno/minimock/blob/master/_autodocs/api-reference/controller.md Calls MinimockFinish() on all registered mockers to verify mocks with expectations have been called. This method is usually unnecessary as Cleanup handles it automatically. ```go mc := minimock.NewController(t) defer mc.Finish() // Usually unnecessary, Cleanup handles this automatically formatterMock := NewFormatterMock(mc) formatterMock.FormatMock.Return("result") // If formatterMock.Format() is never called, the test will fail ``` -------------------------------- ### Mocking Interface with Many Arguments using ExpectParams Source: https://github.com/gojuno/minimock/blob/master/README.md Employ ExpectParams helpers to selectively mock specific arguments of a function with many parameters. This avoids the need to specify all arguments if only a few require checking. ```go type If interface { Do(intArg int, stringArg string, floatArg float) } ``` ```go mc := minimock.NewController(t) ifMock := NewIfMock(mc).DoMock.ExpectIntArgParam1(10).ExpectFloatArgParam3(10.2).Return() ``` -------------------------------- ### NewController Source: https://github.com/gojuno/minimock/blob/master/_autodocs/api-reference/controller.md Creates and returns a new Controller instance. The Controller wraps a Tester (typically *testing.T) and automatically registers a Cleanup function to call Finish() when the test completes. ```APIDOC ## NewController ### Description Creates and returns a new Controller instance. The Controller wraps a Tester (typically `*testing.T`) and automatically registers a Cleanup function to call `Finish()` when the test completes. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Returns - `*Controller` — A new Controller instance ready to register mocks ### Example ```go package main import ( "testing" "github.com/gojuno/minimock/v3" ) func TestMyFunction(t *testing.T) { mc := minimock.NewController(t) // Create mocks with the controller myMock := NewMyInterfaceMock(mc) myMock.SomeMethodMock.Return("result") // All mocks are automatically verified when test completes } ``` ``` -------------------------------- ### Generate Mock using Relative Path Source: https://github.com/gojuno/minimock/blob/master/README.md Generate a mock for an interface using its relative path notation. This is useful when the interface is in a subdirectory. ```bash $ minimock -i ./tests.Formatter ``` -------------------------------- ### Compare Values with Equal Function Source: https://github.com/gojuno/minimock/blob/master/_autodocs/api-reference/equality-and-comparison.md Use this function to compare two values for equality, with special handling for structs and context.Context. It's used by generated mocks for parameter verification. ```go package main import "github.com/gojuno/minimock/v3" import "testing" import "context" func TestEqualFunction(t *testing.T) { // Comparing primitives if minimock.Equal(42, 42) { t.Log("integers are equal") } // Comparing structs type Point struct { X, Y int } p1 := Point{1, 2} p2 := Point{1, 2} if minimock.Equal(p1, p2) { t.Log("structs are equal") } // Using AnyContext for context matching ctx1 := context.Background() ctx2 := context.Background() // Without AnyContext, different contexts won't equal // With AnyContext in params, they will match } ``` -------------------------------- ### Regenerate Specific Package Mocks Source: https://github.com/gojuno/minimock/blob/master/_autodocs/README.md Use this command to regenerate mocks for a specific package. Replace `./mypackage` with the actual path to your package. ```bash # Regenerate specific package go generate ./mypackage ``` -------------------------------- ### Return Method for Setting Return Values Source: https://github.com/gojuno/minimock/blob/master/_autodocs/generated-mock-structure.md Chain the Return method after Expect to specify the value that the mock method should return when called with the expected parameters. Returns the parent mock for further chaining. ```go func (m *mMock) Return(...) *Mock ``` ```go mock.FormatMock.Expect("hello %s", "world").Return("greeting") ``` -------------------------------- ### Handle Unexpected Method Call in Minimock Source: https://github.com/gojuno/minimock/blob/master/_autodocs/errors.md This occurs when a mocked method is called without prior configuration using Expect(), Return(), When/Then(), or Set(). Ensure the method is set up before invocation. ```go mc := minimock.NewController(t) mock := NewFormatterMock(mc) // No setup - this will fail result := mock.Format("hello") // Fatal: Unexpected call to FormatterMock.Format ``` ```go mock := NewFormatterMock(mc) mock.FormatMock.Return("world") // Now configured result := mock.Format("hello") // Works ```