← Back Home

Testing Grpc Service in Go using nettest

  1. go
  2. grpc
  3. networking

Go provides a good httptest implementation for testing HTTP testing .There ar cases where we want to use/test network constructs in Go. This is where nettest comes in picture. Nettest provides more low level implementation for network testing.

I was writing some tests for grpcs services and came across this approach. I created a local TCP listener using nettest and created a new GRPC server using this listener. I provided my service info to this GRPC server and registered it lazily.

func createGRPCClientAndServer(t *testing.T, registrar func(srv *grpc.Server)) (*grpc.ClientConn, func()) {
    // create a local tcp listener using nettest
	lis, err := nettest.NewLocalListener("tcp")
	if err != nil {
		t.Fatalf("failed to get a net test listener: %v", err)
	}

    // create a new grpc server
	s := grpc.NewServer()
    // register grpc service 
	registrar(s)
    // serve in a go routine
	go s.Serve(lis)

    // create a grpc connection
	conn, err := grpc.Dial(lis.Addr().String(), grpc.WithInsecure(), grpc.WithBlock())
	if err != nil {
		t.Fatalf("failed to get a net test listener: %v", err)
	}

    // return grpc connection and func(used to close listener and conn at call site)
	return conn, func() {
		err := lis.Close()
		if err != nil {
			t.Errorf("failed to close test listener: %v", err)
		}
		s.Stop()
		err = conn.Close()
		if err != nil {
			t.Errorf("failed to close grpc connection: %v", err)
		}
	}
}