Go Mocking with Interfaces for Unit Tests

Updated 5 min read
Go Mocking featured image: cards for a small interface, a fake and an httptest server

Go mocking lets you test code that depends on slow services, such as a weather API, without calling them. In this post, you will hide a dependency behind an interface and swap in a fake during tests. Then you will test the real HTTP code with a local test server.

You need two earlier lessons here. First, review Go unit testing for beginners for table-driven tests. Second, revisit interfaces in Go with examples, because interfaces make Go mocking possible.

What Is Go Mocking?

A mock, or fake, is a pretend version of a dependency that you control completely. For example, a fake weather service can say “40 degrees” on demand, even in winter. As a result, your tests run fast, never fail because of the network and can cover rare cases easily.

Think of a flight simulator. Pilots practise engine failures in the simulator, not in a real plane. Similarly, a fake lets you practise errors without breaking anything real.

Step 1: Depend on a Small Interface

// TempSource is the small interface our code depends on.
type TempSource interface {
	Temp(city string) (float64, error)
}

type Advisor struct {
	Source TempSource
}

func (a Advisor) Advice(city string) (string, error) {
	t, err := a.Source.Temp(city)
	if err != nil {
		return "", fmt.Errorf("advice for %s: %w", city, err)
	}
	switch {
	case t >= 35:
		return "Stay indoors and drink water", nil
	case t <= 10:
		return "Wear a warm jacket", nil
	default:
		return "Enjoy the day", nil
	}
}

Advisor never mentions HTTP. Instead, it only knows that something can return a temperature. Because of that, both the real API client and a test fake can plug in. The diagram below shows the two options side by side.

Go Mocking diagram showing an Advisor that depends on an interface implemented by a real client and a test fake

Advisor depends only on the TempSource interface, so production plugs in the HTTP client while tests plug in a fake.

Step 2: Write a Fake for Go Mocking

type fakeSource struct {
	temp  float64
	err   error
	calls []string
}

func (f *fakeSource) Temp(city string) (float64, error) {
	f.calls = append(f.calls, city)
	return f.temp, f.err
}

The fake returns whatever the test asks for. Also, it records each call, so a test can check how the code used it. This hand-written style needs no library at all.

Step 3: Test Every Branch with Go Mocking

func TestAdvice(t *testing.T) {
	tests := []struct {
		name string
		temp float64
		want string
	}{
		{"hot", 40, "Stay indoors and drink water"},
		{"cold", 5, "Wear a warm jacket"},
		{"mild", 24, "Enjoy the day"},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			fake := &fakeSource{temp: tt.temp}
			got, err := Advisor{Source: fake}.Advice("Pune")
			if err != nil {
				t.Fatal(err)
			}
			if got != tt.want {
				t.Errorf("got %q, want %q", got, tt.want)
			}
			if len(fake.calls) != 1 || fake.calls[0] != "Pune" {
				t.Errorf("calls = %v", fake.calls)
			}
		})
	}
}

Each case sets a different temperature, so every branch of the switch runs. In addition, we check that the code asked for the right city exactly once.

Testing the Error Path

func TestAdviceError(t *testing.T) {
	fake := &fakeSource{err: ErrNotFound}
	_, err := Advisor{Source: fake}.Advice("Atlantis")
	if !errors.Is(err, ErrNotFound) {
		t.Fatalf("got %v, want ErrNotFound", err)
	}
}

Errors are hard to trigger with a real service. With Go mocking, however, one field makes the fake fail on purpose.

Step 4: Test the Real Client with httptest

func TestHTTPSource(t *testing.T) {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Query().Get("city") == "Pune" {
			fmt.Fprint(w, `{"celsius": 31.5}`)
			return
		}
		http.NotFound(w, r)
	}))
	defer srv.Close()

	src := HTTPSource{BaseURL: srv.URL, Client: srv.Client()}
	got, err := src.Temp("Pune")
	if err != nil || got != 31.5 {
		t.Fatalf("got %v, %v", got, err)
	}
}

The real HTTPSource still needs a test. So httptest.NewServer starts a tiny local server with your own answers. Therefore, you exercise the real Go HTTP client code without the internet.

$ go test -v -cover .
--- PASS: TestAdvice (0.00s)
    --- PASS: TestAdvice/hot (0.00s)
    --- PASS: TestAdvice/cold (0.00s)
    --- PASS: TestAdvice/mild (0.00s)
--- PASS: TestAdviceError (0.00s)
--- PASS: TestHTTPSource (0.00s)
coverage: 88.2% of statements

Common Mistakes with Go Mocking

Error you seeWhy it happensHow to fix it
fakeSource does not implement TempSource (wrong type for method Temp)Because the fake’s method signature differs.So copy the interface method exactly.
fakeSource does not implement TempSource (method Temp has pointer receiver)Because a value was used where a pointer was needed.So pass &fakeSource{}.
Tests break after every refactorBecause the interface is too big.So keep interfaces small and owned by the caller.

A good rule is “accept interfaces, return structs”. In other words, functions take small interfaces as inputs, which keeps them easy to test. Testing questions appear in most Go interviews, so practise with my Go interview questions and answers.

Official Resources

These pages come straight from the Go team, so they stay accurate and up to date.

Quick Recap

  • Go mocking swaps a real dependency for a fake you control.
  • Depend on a small interface, not a concrete client.
  • A hand-written fake can return values, errors and record calls.
  • Table-driven tests with fakes cover every branch quickly.
  • Use httptest.NewServer to test real HTTP code offline.

What’s Next?

You can now test code that talks to the outside world. Next, we will build fast service-to-service APIs with gRPC and Protocol Buffers.

Coming soon: Building a Go gRPC Service