Sobes.tech
Junior — Middle

Kuidas te testisite koodi, mis suhtleb andmebaasiga?

sobes.tech AI

Vastus AI-lt

To test code interacting with a database in Go, several approaches are used:

  • Mocking the database — create interfaces for working with the database 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) for integration tests.
  • Transactions with rollback — open a transaction in tests, perform operations, and at the end, revert changes to avoid polluting the test environment.

Example of using interface and mocks:

// Interface for working with the database
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.