Mock Solutions for Golang Unit Test

GoMock, httptest, Monkey, GoStub, etc. How to use them? What's the difference?

Stefanie Lai
7 min readOct 25, 2020
by author

In Go develop, Unit Test is inevitable. And it is essential to use Mock when writing Unit Tests.

  • Mock can help test isolate the business logic it depends on, enabling it to compile, link, and run independently.
  • Mock needs Stub. Stub function replaces the real business logic function, returns the required result, and assists the test.

I involved the related test code for Controllers while writing Kubernetes Operator recently, and there would be mocks for GRPC and HTTP requests. I did it in an old fashion way, but I believe there is a better and more graceful way to handle this.

Classify the various scenarios that require mock into the following categories.

  • Global variable
  • Function
  • Interface

And when it comes to details, there will be mocks such as GRPC methods, HTTP requests, etc. However, the appearances may vary, the essence remains unchanged. As long as you master the core theory, it easily helps writing the unit tests.

Common Mock frameworks in Golang.

  • GoMock¹

--

--