1

I'm having difficulties in unit testing the gRPC service in go.

I looked at Testing a gRPC service but it isn't working for me, not sure what I'm doing wrong.

gRPC service implementation for the Add method:

type server struct{}

func main() {
    listener, err := net.Listen("tcp", ":4040")
    if err != nil {
      panic(err)
    }

    srv := grpc.NewServer()
    service.RegisterMathOpServiceServer(srv, &server{})
    reflection.Register(srv)

    if e := srv.Serve(listener); e != nil {
          panic(e)
    }

    fmt.Println("Service is running on localhost:4040")
}

func (s *server) Add(ctx context.Context, request *service.AddRequest) 
(*service.AddResponse, error) {
    a, b := request.GetX(), request.GetY()
    result := a + b

    return &service.AddResponse{Answer: result}, nil
}

Unit Test for the Add method:

package test

import (
    "context"
    pb "mathOp_service/src/service"
    "testing"
)
func TestAddition(t *testing.T) {
    s := server{}   <-- error occurs here
    req := pb.AddRequest{X: int64(1), Y: int64(2)}
    res, err := s.Add(context.Background(), req)

    if res.Answer != 3 {
        t.Error("Expected 1 + 2 to equal 3")
    }
}

Project Directory structure

s := server{} throws an error saying undefined: server.

I'm very new to Go and can't find a solution to fix this.

Junes
  • 85
  • 2
  • 6
  • 1
    Are the packages the same? The unit test must be in the same package as the definition of `server`. – Mark May 26 '19 at 21:30
  • @Mark Yes, They both are in the "main" package. – Junes May 26 '19 at 21:43
  • Based on the referenced SO answer, you need to import your generated protobuf package - typically aliased as `pb`. And refer to your server RPC methods via the `pb` package. – colm.anseo May 26 '19 at 22:02
  • @colminator Thanks. How do I resolve `undefined: server` error? – Junes May 26 '19 at 22:22
  • Looking again at your code, it seems your `service` appears to serve the roll of `pb`, so see @Mark 's comment. The unittest does not have a definition for `type server` - so ensure the source file that contains the definition top line ( `packagw XYZ` etc.) matches that of the test .go file. – colm.anseo May 26 '19 at 22:31
  • If they do match in package name - they must also be in the same directory. – colm.anseo May 26 '19 at 22:33

1 Answers1

1

Looking at your code organization, It seems that you are coming from Java background putting the src and test in there respective folders. I also struggled with the same when I started writing go. What I learned is it is better to have the src and test in the same package and folder therefore, to make the code idiomatic go and it also resolves any variable/methods references within the same package. So in your tests, you only need to import the pb package.

I will also encourage you to look at https://github.com/golang-standards/project-layout for various code organization techniques in Golang.

maverick
  • 1,458
  • 5
  • 20
  • 28