Go Mock Gomock
In this tutorial, you'll learn about Go Mock: gomock Controller. We cover key concepts, practical examples, and best practices.
gomock -- Use gomock for generating and using mock implementations in Go tests.
The Problem
gomock requires controller creation and Finish() call. Forgetting Finish() leads to missed expectation failures. Use defer controller.Finish().
Wrong
ctrl := gomock.NewController(t)
mockSvc := NewMockService(ctrl)
mockSvc.EXPECT().Call().Return("result")
Output:
// Missing Finish(). Expectation failures hidden.
Right
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockSvc := NewMockService(ctrl)
mockSvc.EXPECT().Call().Return("result", nil)
result, _ := mockSvc.Call()
if result != "result" { t.Error(...) }
Output:
// If Call not invoked, test fails on defer
Prevention
- Always defer ctrl.Finish()
- Use NewController(t) for simpler lifecycle
- EXPECT().Return() for expected calls
- EXPECT().Times(1) for call count (default 1)
- EXPECT().AnyTimes() for optional calls
Common Mistakes with mock gomock
- Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
- Using
returnto exit a function early instead of wrapping a pure value in the monad - Mixing let bindings with <- bindings in do notation, producing type errors
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