Catalog My learning Blog
gRPC and Protobuf Tutorial: Fast Microservice APIs · Phase 4 · Lesson 25 · 3 min read

How to Test gRPC Services

On this page
  1. Three levels of gRPC testing
  2. Unit tests: call the handler directly
  3. Integration tests with bufconn: the real stack in memory
  4. Testing streams and deadlines
  5. Schema and contract checks with buf
  6. Check yourself

Three levels of gRPC testing

  • Unit tests call handler methods directly: fast, no networking.
  • In-process integration tests run a real gRPC server and client over an in-memory connection, exercising interceptors, metadata, serialization and status codes.
  • Schema and contract checks make sure the API itself doesn't break callers.

Unit tests: call the handler directly

Go
func newServer() *server {
	return &server{orders: map[string]*shopv1.Order{"ord_42": {Id: "ord_42", TotalCents: 4999}},
		byKey: map[string]*shopv1.Order{}}
}

func TestGetOrder_NotFound(t *testing.T) {
	_, err := newServer().GetOrder(context.Background(), &shopv1.GetOrderRequest{OrderId: "missing"})
	if got := status.Code(err); got != codes.NotFound {
		t.Fatalf("code = %v, want NotFound", got)
	}
}

Assert on status codes, not error strings: codes are the contract (Day 14).

Integration tests with bufconn: the real stack in memory

bufconn provides an in-memory listener, so tests run a real server and client without ports:

Go
func TestGetOrder_OverGRPC(t *testing.T) {
	lis := bufconn.Listen(1 << 20)
	srv := grpc.NewServer(grpc.UnaryInterceptor(authLog))      // the production interceptor
	shopv1.RegisterOrderServiceServer(srv, newServer())
	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() })
	client := shopv1.NewOrderServiceClient(conn)

	tests := []struct {
		name, token, id string
		want            codes.Code
	}{
		{"no token", "", "ord_42", codes.Unauthenticated},
		{"found", "Bearer demo-token", "ord_42", codes.OK},
		{"not found", "Bearer demo-token", "nope", codes.NotFound},
		{"empty id", "Bearer demo-token", "", codes.InvalidArgument},
	}
	for _, tc := range tests {
		t.Run(tc.name, func(t *testing.T) {
			ctx := context.Background()
			if tc.token != "" {
				ctx = metadata.AppendToOutgoingContext(ctx, "authorization", tc.token)
			}
			_, err := client.GetOrder(ctx, &shopv1.GetOrderRequest{OrderId: tc.id})
			if got := status.Code(err); got != tc.want {
				t.Fatalf("code = %v, want %v", got, tc.want)
			}
		})
	}
}
Code
--- PASS: TestGetOrder_NotFound (0.00s)
    --- PASS: TestGetOrder_OverGRPC/no_token (0.00s)
    --- PASS: TestGetOrder_OverGRPC/found (0.00s)
    --- PASS: TestGetOrder_OverGRPC/not_found (0.00s)
    --- PASS: TestGetOrder_OverGRPC/empty_id (0.00s)
--- PASS: TestGetOrder_OverGRPC (0.00s)
ok  	grpclab/server	0.163s

This caught what a unit test can't: the "no token" case is rejected by the interceptor before the handler runs. The passthrough:/// scheme stops the client trying to resolve the fake name with DNS.

Unit tests call handlers directly, in-memory bufconn tests exercise the full gRPC stack including interceptors, and schema checks with buf protect callers from breaking changes.
Unit tests call handlers directly, in-memory bufconn tests exercise the full gRPC stack including interceptors, and schema checks with buf protect callers from breaking changes.

Testing streams and deadlines

  • Streams: in bufconn tests, drive the client side (send, close, receive until io.EOF) and assert on the sequence of messages and the final status.
  • Deadlines and cancellation: call with a short deadline against a deliberately slow fake dependency and assert DEADLINE_EXCEEDED, and that the handler stopped work (Day 15).
  • Fakes for dependencies: generated client interfaces make it easy to substitute fakes; mock generators (gomock, mockery) work too.

Schema and contract checks with buf

  • buf lint and buf breaking in CI on every change (Days 2 and 12).
  • Contract tests between teams: consumers record the requests they make and the fields they rely on, and the provider runs those against its implementation before release.
  • Manual and exploratory testing with grpcurl, grpcui or Postman against a running server with reflection (Day 20).

Check yourself

The real gRPC stack, in memory: interceptors, metadata, serialization, deadlines and status code handling between client and server, without opening network ports.

Codes are part of the API contract that clients depend on; messages are for humans and may be reworded. Tests on messages break for harmless changes and miss real contract changes.

It hands the target string directly to the custom bufconn dialer instead of trying to resolve the fake address through DNS, which would fail. The test then connects to the in-memory server.

Call with a short deadline against a handler that blocks or sleeps, and assert DEADLINE_EXCEEDED and that the handler observed cancellation.

Lint violations, like inconsistent naming, and breaking changes, like a changed field type, in the .proto files before any code is generated or deployed. Running them in CI stops contract problems at the pull request.