How do I mock interfaces in tests in Go?

Mocking interfaces in Go is essential for testing. It allows you to create a controlled environment for your unit tests by simulating the behavior of dependencies. This can help you isolate the functionality you want to test.

Golang, Testing, Mocking, Interfaces, Unit Testing

This guide explains how to mock interfaces in Go, providing examples and best practices for unit testing.

package main import ( "fmt" "testing" ) // Define an interface type Greeter interface { Greet() string } // A struct that implements the Greeter interface type RealGreeter struct{} func (g RealGreeter) Greet() string { return "Hello, World!" } // A mock struct that also implements the Greeter interface type MockGreeter struct { Response string } func (mg MockGreeter) Greet() string { return mg.Response } // Function that uses the Greeter interface func welcome(g Greeter) string { return g.Greet() } // Test function func TestWelcome(t *testing.T) { mockGreeter := MockGreeter{Response: "Mocked Greeting!"} result := welcome(mockGreeter) expected := "Mocked Greeting!" if result != expected { t.Errorf("expected %s, got %s", expected, result) } }

Golang Testing Mocking Interfaces Unit Testing