How do I mock dependencies in fuzz tests for Go?

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

Go fuzz testing mock dependencies unit tests Go testing