Testing a gRPC service

前端 未结 8 523
旧巷少年郎
旧巷少年郎 2020-12-12 15:05

I\'d like to test a gRPC service written in Go. The example I\'m using is the Hello World server example from the grpc-go repo.

The protobuf definition is as follows

8条回答
  •  一生所求
    2020-12-12 15:17

    As a new contributor, I can not comment so I am adding here as an answer.

    The @shiblon answer is the best way to test your service. I am the maintainer of the grpc-for-production and one of the features is an in processing server which makes it easier to work with bufconn.

    Here one example of testing the greeter service

    var server GrpcInProcessingServer
    
    func serverStart() {
        builder := GrpcInProcessingServerBuilder{}
        builder.SetUnaryInterceptors(util.GetDefaultUnaryServerInterceptors())
        server = builder.Build()
        server.RegisterService(func(server *grpc.Server) {
            helloworld.RegisterGreeterServer(server, &testdata.MockedService{})
        })
        server.Start()
    }
    
    //TestSayHello will test the HelloWorld service using A in memory data transfer instead of the normal networking
    func TestSayHello(t *testing.T) {
        serverStart()
        ctx := context.Background()
        clientConn, err := GetInProcessingClientConn(ctx, server.GetListener(), []grpc.DialOption{})
        if err != nil {
            t.Fatalf("Failed to dial bufnet: %v", err)
        }
        defer clientConn.Close()
        client := helloworld.NewGreeterClient(clientConn)
        request := &helloworld.HelloRequest{Name: "test"}
        resp, err := client.SayHello(ctx, request)
        if err != nil {
            t.Fatalf("SayHello failed: %v", err)
        }
        server.Cleanup()
        clientConn.Close()
        assert.Equal(t, resp.Message, "This is a mocked service test")
    }
    

    You can find this example here

提交回复
热议问题