Mocks and interfaces
In Go you mock by defining a small interface and passing a fake implementation in tests. Implicit satisfaction means the production type does not mention the test double. Generated mocks are optional.
Detailed Explanation
A handler that calls Find(ctx, id) should not import a SQL package in its test. It should accept a Finder interface. The test supplies type fakeFinder struct{ u User; err error } with a Find method. That is a fake (it behaves, with no extra framework). A mock also records calls and asserts they happened. Go teams often prefer fakes: less behaviour hidden in a framework.
Interfaces at the consumer. Declare type UserFinder interface { Find(context.Context, string) (User, error) } next to the handler, with the methods the handler uses. The *sql type in another package already has Find or you write a one-line adapter. You do not need a mock library for three methods.
Generated mocks. gomock / mockgen and testify/mock exist. They help when the interface is wide and you care about call order. They hurt when the generated file is larger than a fake and nobody reads the expectations. If you generate, //go:generate next to the interface, and commit the output.
Do not mock *sql.DB. Use a fake repository, or an integration test with a real database. Mocking every SQL method is a snapshot of the query string, not a test of behaviour.
What it costs. A small interface is a design improvement, not only a test trick. A large generated mock freezes a wide interface. Keep the interface narrow and the fake boring.
Code Examples
package api
import (
"context"
"testing"
)
type Finder interface {
Find(ctx context.Context, id string) (string, error)
}
type fake struct {
val string
err error
}
func (f fake) Find(context.Context, string) (string, error) {
return f.val, f.err
}
func lookup(f Finder, id string) (string, error) {
return f.Find(context.Background(), id)
}
func TestLookup(t *testing.T) {
got, err := lookup(fake{val: "ada"}, "1")
if err != nil || got != "ada" {
t.Fatalf("%q %v", got, err)
}
}Common Gotchas
Mocking a 20-method interface means your design is too wide
split it.
`var _ Finder = fake{}` documents that the fake stays in sync
`var _ Finder = fake{}` documents that the fake stays in sync
`httptest` is the fake for HTTP, not a generated mock of `ResponseWriter`
`httptest` is the fake for HTTP, not a generated mock of `ResponseWriter`