Testing gRPC Services

1. Writing Unit Tests for Services

Example: Test service method directly

func TestGetUser(t *testing.T) {
    s := &userServer{repo: newFakeRepo()}
    res, err := s.GetUser(context.Background(), &userv1.GetUserRequest{Id: "u1"})
    require.NoError(t, err)
    require.Equal(t, "Ada", res.Name)
}

2. Using bufconn for In-Memory Server

Example: bufconn listener

import "google.golang.org/grpc/test/bufconn"
lis := bufconn.Listen(1024 * 1024)
srv := grpc.NewServer()
userv1.RegisterUserServiceServer(srv, &userServer{})
go srv.Serve(lis)
conn, _ := grpc.NewClient("passthrough:///bufnet",
    grpc.WithContextDialer(func(_ context.Context, _ string) (net.Conn, error) { return lis.Dial() }),
    grpc.WithTransportCredentials(insecure.NewCredentials()),
)

3. Mocking gRPC Server

ToolDetail
Hand-rolled fakeImplement UnimplementedXServer
gomock + mockgenGenerate from interface
testify/mockExpressive assertions

4. Mocking gRPC Client

Example: mockgen client

mockgen -source=gen/user/v1/user_grpc.pb.go -destination=mocks/user_mock.go

5. Testing Unary RPCs

AssertDetail
Response equalityproto.Equal or cmp with protocmp.Transform()
Error codestatus.Code(err) == codes.NotFound
Error detailsInspect st.Details()

6. Testing Streaming RPCs

Example: Drain server stream

stream, _ := client.ListUsers(ctx, &userv1.ListUsersRequest{})
var got []*userv1.User
for {
    u, err := stream.Recv()
    if errors.Is(err, io.EOF) { break }
    require.NoError(t, err)
    got = append(got, u)
}
require.Len(t, got, 3)

7. Testing Error Cases

CaseDetail
Invalid inputExpect INVALID_ARGUMENT
Missing entityExpect NOT_FOUND
Auth failureExpect UNAUTHENTICATED / PERMISSION_DENIED
TimeoutCancel ctx, expect DEADLINE_EXCEEDED

8. Testing Interceptors

PatternDetail
Call directlyPass fake handler closure
With bufconnEnd-to-end interception

9. Using Test Doubles

DoubleUse
FakeIn-memory repo with real logic
StubHard-coded responses
MockVerifies interaction
SpyRecords calls only

10. Implementing Integration Tests

ToolDetail
testcontainers-goSpin up Postgres/Redis per test
docker composeMulti-service env
grpcurl in scriptsBlack-box smoke tests

11. Implementing Load Tests

ToolDetail
ghzgRPC-native load tester
k6 + xk6-grpcScripted scenarios
Vegeta + gRPC wrapperCustom harness