Golang / GoLang Interfaces and Object Oriented Interview Questions
How do Go interfaces enable dependency injection and improve testability?
Because Go interfaces are satisfied implicitly, any dependency can be injected as an interface. In tests, the interface is replaced with a mock or stub — without any framework, reflection, or code generation.
// Production dependency: HTTP client type HTTPClient interface { Get(url string) (*http.Response, error) } // Service that depends on HTTPClient type WeatherService struct { client HTTPClient apiKey string } func NewWeatherService(client HTTPClient, key string) *WeatherService { return &WeatherService{client: client, apiKey: key} } func (ws *WeatherService) Forecast(city string) (string, error) { url := fmt.Sprintf("https://api.weather.com/%s?key=%s", city, ws.apiKey) resp, err := ws.client.Get(url) // uses injected client if err != nil { return "", err } defer resp.Body.Close() body, _ := io.ReadAll(resp.Body) return string(body), nil } // In tests: mock the HTTPClient interface type MockHTTPClient struct { Response *http.Response Err error } func (m *MockHTTPClient) Get(url string) (*http.Response, error) { return m.Response, m.Err } func TestForecast(t *testing.T) { mock := &MockHTTPClient{ Response: &http.Response{ StatusCode: 200, Body: io.NopCloser(strings.NewReader(`{"temp":"22C"}`)), }, } svc := NewWeatherService(mock, "test-key") result, err := svc.Forecast("London") // Test without any real HTTP calls assert.NoError(t, err) assert.Contains(t, result, "22C") }
Key insight: the mock's Get method satisfies the HTTPClient interface entirely through Go's implicit satisfaction — no mock framework, no code generation, no registration. The production code never imports the test package. This is the idiomatic Go approach to testability.
More Related questions...