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)
}
}
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?