Sobes.tech
Junior — Middle

What is your experience with using mock objects in software testing?

sobes.tech AI

Answer from AI

In my Go development experience, mock objects are used to isolate the code under test from external dependencies such as databases, HTTP services, or the file system. This allows writing fast and reliable unit tests that verify logic without making actual calls to external components.

For example, if you have an interface for working with a database:

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

To test, you can create a mock that implements this interface:

type MockUserRepo struct {}

func (m *MockUserRepo) GetUser(id int) (*User, error) {
    return &User{ID: id, Name: "Test User"}, nil
}
}

In tests, you pass this mock instead of the real repository to control the returned data and check the behavior of functions without depending on the database.

I use both manually written mocks and mock generators (like mockgen) for more complex interfaces.