Senior
How do you generate mocks for unit tests?
sobes.tech AI
Answer from AI
In Go, tools that automatically generate interface mocks based on their descriptions are commonly used. Popular approaches:
- Using
mockgenfrom thegomockpackage- Define the interface.
- Run
mockgento generate mocks. - In tests, create an instance of the mock object and set the expected behavior.
Example:
//go:generate mockgen -source=service.go -destination=mocks/mock_service.go -package=mocks
// In the test
mockCtrl := gomock.NewController(t)
defer mockCtrl.Finish()
mockService := mocks.NewMockMyService(mockCtrl)
mockService.EXPECT().DoSomething(gomock.Any()).Return(nil)
-
Using
testify/mock- Create a struct embedding
mock.Mock. - Define methods calling
mock.Called.
- Create a struct embedding
-
Manual writing of mocks — suitable for simple cases but not scalable.
Automatic mock generation allows for quick updates of stubs when interfaces change and helps maintain clean code.