dongwen4630 2019-05-26 20:05
浏览 851

如何在Go中对gRPC服务进行单元测试

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.

  • 写回答

1条回答 默认 最新

  • douzi2333 2019-05-27 04:12
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog