Sobes.tech
Middle+

How do you generate mocks?

sobes.tech AI

Answer from AI

In Go, mocks are usually generated using specialized tools that create interface implementations for testing.

Popular methods for generating mocks:

  • gomock — the official library from Google. Used together with the mockgen tool, which generates mock structures based on interfaces.

    Example of generation:

    mockgen -source=service.go -destination=mock_service.go -package=service
    
  • mockery — a convenient mock generator that supports various options.

  • moq — a simple mock generator.

Example of using gomock:

import (
    "testing"
    "github.com/golang/mock/gomock"
    "your/module/service"
)

func TestSomething(t *testing.T) {
    ctrl := gomock.NewController(t)
    defer ctrl.Finish()

    mockRepo := service.NewMockUserRepository(ctrl)
    mockRepo.EXPECT().GetUser(1).Return(service.User{ID:1, Name:"Mock User"}, nil)

    // code under test with mockRepo
}

Thus, mock generation allows automating the creation of stubs and simplifies writing tests with dependency isolation.