When benchmarking in Go, it's important to ensure that dependencies are mocked to isolate the function or method being tested. This improves the accuracy of your benchmarks by eliminating the influence of external factors. Here's how you can do it effectively.
package main
import (
"testing"
"github.com/stretchr/testify/mock"
)
// Step 1: Create an interface for the dependency
type Database interface {
GetData(id int) string
}
// Step 2: Create a mock struct that implements the interface
type MockDatabase struct {
mock.Mock
}
func (m *MockDatabase) GetData(id int) string {
args := m.Called(id)
return args.String(0)
}
// Step 3: The function to benchmark
func FetchData(db Database, id int) string {
return db.GetData(id)
}
// Step 4: Write the benchmark
func BenchmarkFetchData(b *testing.B) {
mockDB := new(MockDatabase)
mockDB.On("GetData", 1).Return("mocked data")
for i := 0; i < b.N; i++ {
FetchData(mockDB, 1)
}
mockDB.AssertExpectations(b)
}
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?