我想测试一个 Go 编写的 gRPC 服务。我用的例子来自grpc-go repo的 Hello World 服务器示例。! d% c* D3 K6 x% O$ P! ]3 A" r
protobuf 定义如下:" _+ r& L* Y0 E) W
syntax = "proto3";package helloworld;// The greeting service definition.service Greeter { / Sends a greeting rpc SayHello (HelloRequest) returns (HelloReply) {}/ The request message containing the user's name.message HelloRequest { string name = 1;}// The response message containing the greetingsmessage HelloReply { string message = 1;}# R$ t) B, j4 [
greeter_server主要类型为:/ ^0 Y3 n2 D8 j4 L! j; ~8 W. Z
// server is used to implement helloworld.GreeterServer.type server struct{}// SayHello implements helloworld.GreeterServerfunc (s *server) SayHello(ctx context.Context,in *pb.HelloRequest) (*pb.HelloReply,error) return &pb.HelloReply{Message: "Hello " in.Name},nil} . l O9 j, \, y3 W! r
我已经找到了一个例子,但是我找不到任何关于如何在 Go 中实现 gRPC 服务测试示例。+ N1 @9 D$ J" ^" I
+ C6 X" Q/ j/ C& o8 H8 q6 O0 ?解决方案: # p# C4 F# p x; s4 }- g6 J; B
我想你正在寻找它google.golang.org/grpc/test/bufconn包帮助您避免使用真实的端口号启动服务,但仍允许测试流式 RPC。6 X3 w5 \( g! O- f
import "google.golang.org/grpc/test/bufconn"const bufSize = 1024 * 1024var lis *bufconn.Listenerfunc init() lis = bufconn.Listen(bufSize) s := grpc.NewServer() pb.RegisterGreeterServer(s,&server go func() if err := s.Serve(lis); err != nil log.Fatalf("Server exited with error: %v",err) } }()}func bufDialer(context.Context,string) (net.Conn,error) return lis.Dial()}func TestSayHello(t *testing.T) ctx := context.Background() conn,err := grpc.DialContext(ctx,"bufnet",grpc.WithContextDialer(bufDialer),grpc.WithInsecure() if err != nil t.Fatalf("Failed to dial bufnet: %v",err) } defer conn.Close() client := pb.NewGreeterClient(conn) resp,err := client.SayHello(ctx,&pb.HelloRequest{"Dr. Seuss"}) if err != nil t.Fatalf("SayHello failed: %v",err) } log.Printf("Response: % v",resp) // Test for output here.}9 F/ q/ @8 L7 {