Sobes.tech
Middle+

What is a mock?

sobes.tech AI

Answer from AI

Mock (mock) is a stub object that simulates the behavior of a real object in tests. Mocks are used to isolate the code under test from external dependencies to verify logic without executing complex or external operations.

In Go, mocks are often created manually or with generators (e.g., mockgen). They implement interfaces used by the tested code and allow setting expected calls and return values.

Example of a simple interface mock:

// Interface
type UserRepository interface {
    GetUser(id int) (*User, error)
}

// Mock
type MockUserRepo struct {
    Users map[int]*User
}

func (m *MockUserRepo) GetUser(id int) (*User, error) {
    if user, ok := m.Users[id]; ok {
        return user, nil
    }
    return nil, errors.New("user not found")
}

This mock can be used in tests to control the behavior of the repository without a real database.