Go Mock Testify Mock
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.
Right
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
- 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