Simple Go Interface Contract Example

package main

import (
	"fmt"
)

// contract
// Greeter interface defines the contract for greeting functionality
type Greeter interface {
	Hello() string
}

// usage
// Example usage function that depends on the Greeter interface
func PrintGreeting(g Greeter) string {
	return g.Hello()
}

func main() {

	// notice how PrintGreeting taking two different implementations of the same interface

	// Using mock implementation
	mockG := &MockGreeter{Name: "mock"}
	fmt.Println(PrintGreeting(mockG))

	// Using real implementation
	real := &RealGreeter{Name: "real"}
	fmt.Println(PrintGreeting(real))

	fmt.Printf("Mock was called %d time(s)\n", mockG.CallCount)
}

// implementation
// RealGreeter is a concrete implementation of the Greeter interface
type RealGreeter struct {
	Name string
}

// Hello returns a greeting message
func (g *RealGreeter) Hello() string {
	return fmt.Sprintf("Hello, %s!", g.Name)
}

// mock implementation
// MockGreeter is a simple mock implementation for testing
type MockGreeter struct {
	CallCount int
	Name      string
}

func (m *MockGreeter) Hello() string {
	m.CallCount++
	return fmt.Sprintf("Hello, %s!", m.Name)
}

Posted

in

by

Tags: