In Go, fuzz testing is a powerful way to find bugs by providing random data to your functions. When working with dependencies in fuzz tests, you may need to create mock implementations of these dependencies to isolate the unit under test. This can help in ensuring that your tests are robust and focused on the functionality of the code you're testing.
To mock dependencies in fuzz tests, you can use interfaces that define the behaviors of the dependencies. Then, you can create a mock implementation of these interfaces for your tests. Here's a simple example:
package main
import (
"fmt"
"testing"
)
// Define the interface for the dependency
type Database interface {
GetUser(id string) (string, error)
}
// Mock implementation of the Database interface
type MockDatabase struct {
UserData map[string]string
}
func (m *MockDatabase) GetUser(id string) (string, error) {
user, exists := m.UserData[id]
if !exists {
return "", fmt.Errorf("user not found")
}
return user, nil
}
// Function to be tested
func FetchUser(db Database, id string) (string, error) {
return db.GetUser(id)
}
// Fuzz test for FetchUser
func FuzzFetchUser(f *testing.F) {
// Add seed corpus
f.Add("123", "John Doe")
f.Add("456", "Jane Doe")
f.Fuzz(func(t *testing.T, id string, name string) {
mockDB := &MockDatabase{
UserData: map[string]string{id: name},
}
user, err := FetchUser(mockDB, id)
if err != nil && name != "" {
t.Errorf("expected user to be found, got error: %v", err)
}
if user != name {
t.Errorf("expected %s, got %s", name, user)
}
})
}
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?