-
Notifications
You must be signed in to change notification settings - Fork 0
/
example_test.go
79 lines (67 loc) · 2.33 KB
/
example_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package grpcmock_test
import (
"context"
"log"
"net"
"github.com/soroushj/grpcmock"
"github.com/soroushj/grpcmock/example/notes"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
func Example() {
// Create a gRPC server using a grpcmock interceptor
mock := grpcmock.New()
server := grpc.NewServer(grpc.UnaryInterceptor(mock.UnaryServerInterceptor()))
// Register an implementation of your server; the example Notes server in this case.
// This typically should be the generated Unimplemented implementation.
notes.RegisterNotesServer(server, ¬es.UnimplementedNotesServer{})
// Run the server on an available port
lis, err := net.Listen("tcp", ":0")
if err != nil {
log.Fatalf("listen: %v", err)
}
go func() {
if err := server.Serve(lis); err != nil {
log.Fatalf("serve at %v: %v", lis.Addr(), err)
}
}()
// At this point, if you call any method from the running server, you will get an Unimplemented error.
// Let's change this behavior for the GetNote method of this server.
// This is how you can set a mock response for a method; an error in this case.
// After this, you will get a NotFound error from GetNote instead of an Unimplemented error.
mock.SetResponse("GetNote", &grpcmock.UnaryResponse{
Err: status.Error(codes.NotFound, "note not found"),
})
// Similarly, you can set a non-error response.
// After this, you will get the response below from GetNote instead of an error.
mock.SetResponse("GetNote", &grpcmock.UnaryResponse{
Resp: ¬es.GetNoteResponse{
Note: ¬es.Note{
Id: "1",
Text: "a",
},
},
})
// If you need something more than a simple response, you can set a handler.
// After this, any call to GetNote will be handled using the function below.
mock.SetHandler("GetNote", func(ctx context.Context, req interface{}) (interface{}, error) {
r := req.(*notes.GetNoteRequest)
if r.Id == "1" {
return ¬es.GetNoteResponse{
Note: ¬es.Note{
Id: "1",
Text: "a",
},
}, nil
}
return nil, status.Error(codes.NotFound, "note not found")
})
// You can remove any previously-set response or handler for a method.
// After this, GetNote will return an Unimplemented error.
mock.Unset("GetNote")
// You can also remove any response or handler for all methods
mock.Clear()
// Stop the server
server.Stop()
}