Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 39 ยท Testing and Versioning

Testing gRPC Services

Test gRPC servers and clients in Go: handler unit tests, in-memory bufconn connections, fake clients, status code assertions, deadlines and streaming, with runnable examples.

A gRPC service is easy to test because the interesting part is just a Go interface. The generated code gives you a UserServiceServer interface for the server and a UserServiceClient interface for the client. You can test at three levels, each trading speed for realism:

  1. Handler unit tests: call the method directly with a context and a request message. No network, microsecond fast.
  2. In-process integration tests: start a real gRPC server on an in-memory listener (bufconn) and call it through a real client. This exercises serialization, interceptors, metadata, deadlines and status codes without opening a port.
  3. End-to-end tests: the real binary, real network, real dependencies, in a test environment.

Most of your tests should live in levels 1 and 2.

The grpc-go test helpers cannot run on this site, so they are shown read-only. The runnable examples use the same structure (interfaces, fakes, table tests, in-memory transport via net.Pipe) with only the standard library.

Level 1: test the handler directly

Because a handler is func(ctx, *Request) (*Response, error), you can call it like any method. Keep business logic in a plain type that the handler delegates to, and inject dependencies through interfaces so you can substitute fakes.

Go
func TestGetUser_NotFound(t *testing.T) {
    s := &server{repo: fakeRepo{}}            // repo returns ErrNotFound
    _, err := s.GetUser(context.Background(), &pb.GetUserRequest{Id: "nope"})
    if got := status.Code(err); got != codes.NotFound {
        t.Fatalf("code = %v, want NotFound", got)
    }
}

Always assert the status code, never the message text. Messages are for humans and change freely (see status codes).

Go Table-driven handler tests

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Level 2: bufconn, a real server in memory

google.golang.org/grpc/test/bufconn provides a listener whose connections live in memory. Your test starts the real server on it and dials with a custom dialer:

Go
const bufSize = 1 << 20

func newTestClient(t *testing.T, register func(*grpc.Server)) *grpc.ClientConn {
    lis := bufconn.Listen(bufSize)
    srv := grpc.NewServer(grpc.ChainUnaryInterceptor(authInterceptor)) // the real interceptors!
    register(srv)
    go srv.Serve(lis)
    t.Cleanup(srv.Stop)

    conn, err := grpc.NewClient("passthrough:///bufnet",
        grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) {
            return lis.DialContext(ctx)
        }),
        grpc.WithTransportCredentials(insecure.NewCredentials()),
    )
    if err != nil {
        t.Fatal(err)
    }
    t.Cleanup(func() { conn.Close() })
    return conn
}

func TestAuth(t *testing.T) {
    conn := newTestClient(t, func(s *grpc.Server) { pb.RegisterUserServiceServer(s, newServer()) })
    client := pb.NewUserServiceClient(conn)

    _, err := client.GetUser(context.Background(), &pb.GetUserRequest{Id: "1"})
    if status.Code(err) != codes.Unauthenticated {
        t.Fatalf("want Unauthenticated, got %v", err)
    }

    ctx := metadata.AppendToOutgoingContext(context.Background(), "authorization", "Bearer test-token")
    if _, err := client.GetUser(ctx, &pb.GetUserRequest{Id: "1"}); err != nil {
        t.Fatal(err)
    }
}

Register the same interceptors as production so tests cover authentication and recovery. Use t.Cleanup so servers always stop, and use srv.Stop (not GracefulStop) in tests to avoid hangs.

What an in-memory transport looks like

This runnable stand-in uses net.Pipe the way bufconn uses its buffers: a server goroutine and a client talk through an in-memory connection with a tiny length-prefixed protocol, and the test checks both a success and an error path.

Go An in-memory client and server

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Testing streams

For streaming RPCs, test the happy path and the interruptions: receive until io.EOF, cancel the context mid-stream, and make the server return an error after a few messages. Remember that the final status only arrives with the last Recv.

Go
stream, err := client.ListUsers(ctx, &pb.ListUsersRequest{})
if err != nil { t.Fatal(err) }
var got []string
for {
    u, err := stream.Recv()
    if err == io.EOF { break }
    if err != nil { t.Fatal(err) }
    got = append(got, u.GetName())
}

Fakes for clients

When you test code that calls a gRPC service, replace the client with a fake that implements the generated UserServiceClient interface. Embed the interface so you only implement the methods you need:

Go
type fakeUsers struct {
    pb.UserServiceClient              // nil; calling an unimplemented method panics, which flags a missing stub
    getUser func(*pb.GetUserRequest) (*pb.User, error)
}

func (f fakeUsers) GetUser(ctx context.Context, in *pb.GetUserRequest, _ ...grpc.CallOption) (*pb.User, error) {
    return f.getUser(in)
}
Go Test failure handling with a fake client

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Testing with real tools

  • grpcurl exercises a running server from scripts and CI (needs reflection or proto files).
  • ghz is a load-testing tool (see load testing).
  • Run tests with -race; gRPC servers are concurrent by nature.
  • Test deadline behaviour by calling a deliberately slow fake with a short context, and assert DEADLINE_EXCEEDED.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What should a test assert about an error from a gRPC call?

    Codes are part of the contract; messages are for humans and may change.
  2. 2. What is bufconn used for?

    bufconn gives a fast, hermetic transport for integration tests that still exercises serialization and interceptors.
  3. 3. Why register production interceptors in integration tests?

    Tests should resemble production. Skipping interceptors leaves their behaviour unverified.
  4. 4. How do you build a fake gRPC client quickly?

    Embedding the interface satisfies it, and methods you did not stub panic if called, which reveals missing stubs.

Summary

  • Test at three levels: handler unit tests, in-process integration tests with bufconn, and a few end-to-end tests.
  • Assert status codes, not messages.
  • Use the same interceptors in tests as in production; clean up with t.Cleanup.
  • Test streams for EOF, cancellation and late errors; run with -race.
  • Replace clients with fakes by embedding the generated interface.

Next: Protobuf Schema Evolution