Middle
What is a mock object (stub) in testing?
sobes.tech AI
Answer from AI
A mock object (stub) in testing is a special object that simulates the behavior of a real component or system module. It is used to isolate the code under test from external dependencies to verify the logic without the influence of real services or resources.
For example, if you have a function that accesses a database, in tests, instead of a real connection, you can use a mock object that returns predefined data. This speeds up tests and makes them more reliable.
Example in Go using interface and mock:
// Interface for database operations
type UserRepository interface {
GetUser(id int) (*User, error)
}
// Mock implementation
type MockUserRepo struct {}
func (m *MockUserRepo) GetUser(id int) (*User, error) {
return &User{ID: id, Name: "Test User"}, nil
}
// In test
func TestGetUserName(t *testing.T) {
repo := &MockUserRepo{}
user, err := repo.GetUser(1)
if err != nil {
t.Fatal(err)
}
if user.Name != "Test User" {
t.Errorf("expected Test User, got %s", user.Name)
}
}
Thus, mock objects help create a controlled environment for testing and identify errors in logic without depending on external systems.