Skip to content

Go Mock Gomock

DodaTech 1 min read

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

  1. Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
  2. Using return to exit a function early instead of wrapping a pure value in the monad
  3. 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

**What is the difference between gomock and testify?**

gomock generates mocks. testify/mock uses manual mock structs.

Can I expect calls in order?

Yes. gomock.InOrder(mock.EXPECT().Call1(), mock.EXPECT().Call2()).

How to match arguments?

Use gomock.Eq(), gomock.Any(), gomock.Not().


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