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)
}
})
}
}
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
