Middle+
Mis on mock (võlts)?
sobes.tech AI
Vastus AI-lt
Mock (moc) — this is a placeholder object that mimics the behavior of a real object during tests. Mocks are used to isolate the tested code from external dependencies, allowing 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 defining 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.