Junior — Middle
Каким образом вы проводили тестирование кода, который взаимодействует с базой данных?
sobes.tech AI
Answer from AI
Several approaches are used for testing code that interacts with a database in Go:
- Mocking the database — create interfaces for database operations and replace real calls with mocks to test logic without a real database.
- Test databases — use a separate test database or in-memory databases (e.g., SQLite) to perform integration tests.
- Transactions with rollback — open a transaction in tests, perform operations, and rollback at the end to avoid polluting the test environment.
Example of using interfaces and mocks:
// Interface for database operations
type UserRepository interface {
GetUser(id int) (*User, error)
}
// Creating a mock in tests
type MockUserRepo struct {}
func (m *MockUserRepo) GetUser(id int) (*User, error) {
return &User{ID: id, Name: "Test"}, nil
}
This approach allows isolating the code under test from the real database.