Sobes.tech
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:

  1. Using mockgen from the gomock package
    • Define the interface.
    • Run mockgen to 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)
  1. Using testify/mock

    • Create a struct embedding mock.Mock.
    • Define methods calling mock.Called.
  2. 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.