package main import ( "context" "net" "testing" pb "git.strikerlulu.me/strikerlulu/grpc-mocker/pb" "github.com/stretchr/testify/assert" "google.golang.org/grpc" "google.golang.org/grpc/reflection" "google.golang.org/grpc/test/bufconn" ) type mockServer struct { pb.UnimplementedCalcServiceServer response *pb.AdditionResponse err error } func (s *mockServer) Add(ctx context.Context, req *pb.AdditionRequest) (*pb.AdditionResponse, error) { return s.response, s.err } func TestCalcService(t *testing.T) { bufSize := 1024 * 1024 listener := bufconn.Listen(bufSize) // Create a gRPC server and register the mock service server := grpc.NewServer() mock := &mockServer{ response: &pb.AdditionResponse{Result: 3}, err: nil, } pb.RegisterCalcServiceServer(server, mock) reflection.Register(server) go func() { if err := server.Serve(listener); err != nil { t.Fatalf("server failed to start: %v", err) } }() // Create a gRPC client to use in tests conn, err := grpc.DialContext(context.Background(), "bufnet", grpc.WithContextDialer(func(context.Context, string) (net.Conn, error) { return listener.Dial() }), grpc.WithInsecure()) if err != nil { t.Fatalf("failed to dial bufnet: %v", err) } client := pb.NewCalcServiceClient(conn) resp, err := client.Add(context.Background(), &pb.AdditionRequest{X: 5,Y: 5}) assert.NoError(t, err) // we get mocker 3 instead of 5 assert.Equal(t, uint64(3), resp.Result) server.Stop() }