Skip to content

Go Mock Testify Mock

DodaTech 1 min read

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

testify/mock -- Use testify's mock package for manual mock implementations.

The Problem

testify/mock requires calling AssertExpectations(t) to verify expected calls were made. Use mockObj.AssertExpectations(t) in a deferred cleanup.

Wrong

type MockService struct {
    mock.Mock
}
func (m *MockService) Call() (string, error) {
    args := m.Called()
    return args.String(0), args.Error(1)
}

Output:

// Expectations not asserted. Mock calls not verified.
func TestService(t *testing.T) {
    mockSvc := new(MockService)
    mockSvc.On("Call").Return("result", nil)
    svc := NewService(mockSvc)
    result, _ := svc.DoSomething()
    mockSvc.AssertExpectations(t) // Verify all expectations met
}

Output:

// Test passes only if all expected calls were made

Prevention

  • Use mockObj.On("Method").Return(...) to set expectations
  • Call AssertExpectations(t) at end of test
  • Use mockObj.AssertCalled(t, "Method", args...) for verification
  • Use assert.NotCalled for negative testing
  • testify mocks are manual (no code generation needed)

Common Mistakes with mock testify mock

  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 to handle variable arguments?**

Use mock.Method with matched.Anything or matched.Arguments.

Can I mock interface methods?

Yes. Embed mock.Mock in a struct implementing the interface.

How to assert call order?

Use testify's assert.ObjectsAreEqual or manual call counters.


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