How do I mock dependencies in unit tests for Go?

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.

Example of Mocking in Go


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!")
}
    

Mocking dependencies Go testing unit tests interfaces mock libraries