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.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
