1

I have the following code in Go:

func (s UserServer) getUser(user string) (*User, error) {
    conn, err := grpc.DialContext(ctx, s.userSvcAddr,
        grpc.WithInsecure(),
        grpc.WithStatsHandler(&ClientHandler{}))
    if err != nil {
        return nil, fmt.Errorf("could not get the user: %+v", err)
    }
    defer conn.Close()

    user, err := s.NewUser(conn)
    return user, nil
}

How to mock the grpc.DialContext in the unit test?

isherwood
  • 58,414
  • 16
  • 114
  • 157
ratzip
  • 1,571
  • 7
  • 28
  • 53
  • 1
    What have you tried? Options range from using of `google.golang.org/grpc/test/bufconn` (so `DialContext` actually runs as-is - see [this answer](https://stackoverflow.com/a/52080545/11810946)) through to adding something like `var dialer = grpc.DialContext` and substituting that in tests. Note that connecting on every call is relatively expensive; its more common to connect at startup and reuse the connection. – Brits Feb 25 '22 at 21:52

0 Answers0