Skip to content

Go Mock Counterfeiter

DodaTech 1 min read

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
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

  1. Forgetting deriving (Show, Eq) on custom data types needed for debugging
  2. Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
  3. Using head and tail instead 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

**How is counterfeiter different from gomock?**

Counterfeiter generates fakes (spies). gomock generates mocks (expectations).

Can I inspect call arguments?

Yes. fake.MethodArgsForCall(index) returns the arguments.

Does counterfeiter support generic interfaces?

Yes (Go 1.18+). Generated fakes handle type parameters.


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