Junior — Middle
Mocks in testing and why are they needed?
sobes.tech AI
Answer from AI
Mocks in testing are stub objects that imitate the behavior of real system dependencies. They are used to isolate the code under test from external components, ensuring that tests are fast, reliable, and reproducible.
For example, if a function depends on a database, instead of a real connection, a mock can be used that returns predefined data. This allows testing the function's logic without the risk of failures due to database issues.
In Go, mocks are often created using interfaces and specialized libraries such as gomock or testify/mock.
Example of a simple mock in Go:
// Interface
type DB interface {
GetUser(id int) (User, error)
}
// Mock
type MockDB struct {}
func (m *MockDB) GetUser(id int) (User, error) {
return User{ID: id, Name: "Test User"}, nil
}
// In a test
func TestGetUserName(t *testing.T) {
db := &MockDB{}
user, err := db.GetUser(1)
if err != nil {
t.Fatal(err)
}
if user.Name != "Test User" {
t.Errorf("unexpected user name")
}
}