Skip to content

Go Mock Minimock

DodaTech 1 min read

In this tutorial, you'll learn about Go Mock: minimock Library. We cover key concepts, practical examples, and best practices.

minimock -- Use minimock for clean, readable mock implementations with Go's code generation.

The Problem

minimock generates mock implementations from interfaces. After changing the interface, regenerate mocks with go generate.

Wrong

//go:generate minimock -i Service -o ./mocks/
type Service interface {
    Call(ctx context.Context, id int) (string, error)
}

Output:

// After changing Service interface, mock is outdated
// Run: go generate ./...
mockService := minimock.NewServiceMock(t)
mockService.CallMock.Expect(ctx, 42).Return("result", nil)
result, err := mockService.Call(ctx, 42)

Output:

// Clean, readable mock expectations

Prevention

  • Use //go:generate minimock -i Interface -o ./mocks/
  • Regenerate after interface changes
  • Cleaner API: .Mock.Expect(args).Return(results)
  • Supports .Set for custom handler functions
  • Integrates with testing.T for cleanup

Common Mistakes with mock minimock

  1. Misunderstanding that String is [Char] with poor performance for large text operations
  2. Using foldl instead of foldl' causing stack overflow on large lists
  3. Forgetting deriving (Show, Eq) on custom data types needed for debugging

These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

**What is different about minimock?**

Cleaner API than gomock. No controller.Finish() needed.

Can I verify call counts?

Yes. mockService.CallMock.Set(handler). WaitFor(expectedCount).

How to handle unexpected calls?

minimock fails the test on unexpected calls by default.


Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro