A small testing library for gRPC-Go servers
grpctest provides a test server and client connection. The server response from a given client request is obtained with trivial setup, reducing the overhead of testing a gRPC service.
This test server is intended to be used along side the protocol compiler plugins, protoc-gen-go and protoc-gen-go-grpc to generate the relevant code. Familiarity with this process is assumed in the instructions below to further simplify setup. The following uses the gRPC quickstart greeter server as an example.
Install the necessary prerequistes and create a test file. Import grpctest.
import "github.com/atoscerebro/grpctest"
Define a test function. A test server can be initialised with context.
func TestSayHello(t *testing.T) {
ctx := context.Background()
s := grpctest.NewServer().WithContext(ctx)
defer s.Close()
}
Import the relevant generated protobuf package.
import pb "google.golang.org/grpc/examples/helloworld/helloworld"
Register the greeter server using the generated function with s.RunServer()
.
s.RunServer(t, func(s *grpc.Server) {
pb.RegisterGreeterServer(s, &server{})
})
Initialise a new Greeter client with s.ClientConn()
client := pb.NewGreeterClient(s.ClientConn(t))
With all the necesssary setup complete, the client can now make a request.
reply, err := client.SayHello(ctx, &pb.HelloRequest{Name: "Alice"})
The reply and any errors can be tested accordingly.
if err != nil {
t.Fatalf("SayHello failed: %v", err)
}
expected := "Hello Alice"
if actual := reply.GetMessage(); actual != expected {
t.Errorf(`got "%s", want "%s"`, actual, expected)
}