Member-only story
Mock Solutions for Golang Unit Test
GoMock, httptest, Monkey, GoStub, etc. How to use them? What's the difference?
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¹
- Go httptest
- GoStub²
- GoMonkey³
- Testify⁴
Generally speaking, the straightest method is to implement Mock by defining an interface, which you can use with the other frameworks of GoStub, GoMock, and GoMonkey in pairs or groups.
Testify is a relatively more comprehensive test framework with separate Mock support. You can use it either with your own framework or with the Mock frameworks listed above.
Go httptest, is the official Golang framework for Mock HTTP requests.
Now I will analyze the Mock support of each framework from several perspectives.
- Mock a global variable
- Mock an interface
- Mock a function, with return value or without a return value.