Testing a gRPC service

前端 未结 8 522
旧巷少年郎
旧巷少年郎 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:27

    I came up with the following implementation which may not be the best way of doing it. Mainly using the TestMain function to spin up the server using a goroutine like that:

    const (
        port = ":50051"
    )
    
    func Server() {
        lis, err := net.Listen("tcp", port)
        if err != nil {
            log.Fatalf("failed to listen: %v", err)
        }
        s := grpc.NewServer()
        pb.RegisterGreeterServer(s, &server{})
        if err := s.Serve(lis); err != nil {
            log.Fatalf("failed to serve: %v", err)
        }
    }
    func TestMain(m *testing.M) {
        go Server()
        os.Exit(m.Run())
    }
    

    and then implement the client in the rest of the tests:

    func TestMessages(t *testing.T) {
    
        // Set up a connection to the Server.
        const address = "localhost:50051"
        conn, err := grpc.Dial(address, grpc.WithInsecure())
        if err != nil {
            t.Fatalf("did not connect: %v", err)
        }
        defer conn.Close()
        c := pb.NewGreeterClient(conn)
    
        // Test SayHello
        t.Run("SayHello", func(t *testing.T) {
            name := "world"
            r, err := c.SayHello(context.Background(), &pb.HelloRequest{Name: name})
            if err != nil {
                t.Fatalf("could not greet: %v", err)
            }
            t.Logf("Greeting: %s", r.Message)
            if r.Message != "Hello "+name {
                t.Error("Expected 'Hello world', got ", r.Message)
            }
    
        })
    }
    

提交回复
热议问题