Go Mock Counterfeiter
In this tutorial, you'll learn about Go Mock: counterfeiter. We cover key concepts, practical examples, and best practices.
counterfeiter -- Use counterfeiter to generate realistic fakes from interfaces for testing.
The Problem
counterfeiter generates fakes that record calls and can return specified values. It also generates a Fake with spy capabilities.
Wrong
//go:generate go run github.com/maxbrunsfeld/counterfeiter/v6 . Service
type Service interface {
Call(ctx context.Context, id int) (string, error)
}
Output:
// After interface changes, regenerate fakes
Right
fake := &fakes.FakeService{}
fake.CallReturns("result", nil)
result, err := fake.Call(ctx, 42)
fmt.Println(fake.CallCallCount()) // 1
Output:
// Recorded call count, args, and returns
Prevention
- Use go generate to create fakes
- Fakes track calls: CallCount(), Calls() arguments
- Set returns: MethodReturns(value, error)
- Set stub: MethodStub = func(...) ... for custom logic
- Works with any interface in any package
Common Mistakes with mock counterfeiter
- Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists
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
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