In Go (Golang), mocking dependencies in unit tests is a common practice that allows you to isolate the functionality being tested. Mocking can be done using various techniques, including creating interfaces, using third-party mock libraries, or manually creating mock types.
package main
import (
"fmt"
"testing"
)
// Database interface
type Database interface {
Connect() string
}
// RealDatabase implements Database
type RealDatabase struct{}
func (r *RealDatabase) Connect() string {
return "Connected to real database"
}
// MockDatabase implements Database for testing
type MockDatabase struct{}
func (m *MockDatabase) Connect() string {
return "Connected to mock database"
}
// Service using the Database interface
type Service struct {
db Database
}
func (s *Service) GetConnection() string {
return s.db.Connect()
}
// Unit test
func TestGetConnection(t *testing.T) {
mockDB := &MockDatabase{}
service := &Service{db: mockDB}
connection := service.GetConnection()
if connection != "Connected to mock database" {
t.Errorf("Expected mock connection, got %s", connection)
}
}
func main() {
fmt.Println("Hi there!")
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?