Test gRPC services in Go by creating a test server with httptest.NewUnstartedServer, enabling HTTP/2, and using a custom http.Transport configured for HTTP/2 to make requests.
package main
import (
"crypto/tls"
"net/http"
"net/http/httptest"
"testing"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
func TestGRPCService(t *testing.T) {
// 1. Create a test server with HTTP/2 enabled
ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Handle gRPC request logic here
w.WriteHeader(http.StatusOK)
}))
ts.EnableHTTP2 = true
ts.StartTLS()
defer ts.Close()
// 2. Create a gRPC client connected to the test server
conn, err := grpc.Dial(ts.Listener.Addr().String(),
grpc.WithTransportCredentials(insecure.NewCredentials()),
grpc.WithContextDialer(func(ctx context.Context, addr string) (net.Conn, error) {
return net.Dial("tcp", ts.Listener.Addr().String())
}),
)
if err != nil {
t.Fatalf("Failed to dial: %v", err)
}
defer conn.Close()
// 3. Use the client to call your gRPC methods
// client := pb.NewMyServiceClient(conn)
// resp, err := client.MyMethod(ctx, &pb.Request{})
// if err != nil { t.Fatal(err) }
}