Golang / GoLang System Architecture and Testing Interview Questions
How do you write unit and integration tests for gRPC services in Go?
gRPC services are tested at multiple levels: unit tests using the generated client/server with an in-process buffer connection, and integration tests using a real server. The bufconn package provides a lightweight in-memory network for fast unit tests.
import ( "google.golang.org/grpc" "google.golang.org/grpc/test/bufconn" ) const bufSize = 1024 * 1024 // Setup: start server in-process with bufconn func setupTestServer(t *testing.T, repo UserRepository) pb.UserServiceClient { t.Helper() lis := bufconn.Listen(bufSize) grpcServer := grpc.NewServer() pb.RegisterUserServiceServer(grpcServer, &userServiceServer{repo: repo}) go func() { if err := grpcServer.Serve(lis); err != nil { t.Logf("server error: %v", err) } }() t.Cleanup(func() { grpcServer.GracefulStop() }) // Dial using the in-memory buffer 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.Fatalf("dial: %v", err) } t.Cleanup(func() { conn.Close() }) return pb.NewUserServiceClient(conn) } // Table-driven gRPC test func TestGetUser(t *testing.T) { fakeRepo := &fakeUserRepo{ users: map[int]*User{1: {ID: 1, Name: "Alice"}}, } client := setupTestServer(t, fakeRepo) tests := []struct { name string id int64 wantName string wantCode codes.Code }{ {"existing user", 1, "Alice", codes.OK}, {"missing user", 99, "", codes.NotFound}, {"invalid id", 0, "", codes.InvalidArgument}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { resp, err := client.GetUser(context.Background(), &pb.GetUserRequest{Id: tt.id}) if code := status.Code(err); code != tt.wantCode { t.Errorf("got code %v, want %v", code, tt.wantCode) } if tt.wantName != "" && resp.Name != tt.wantName { t.Errorf("got name %q, want %q", resp.Name, tt.wantName) } }) } }
More Related questions...