Configurable CallInvoker that can be used to intercept and return desired response for the cases where we need a mocked behavior.
Currently only Unary calls are supported.
Depending on how you are setting up your gRPC services using a DI or doing it manually setup will differ. The example below will show how set it up manually, but using DI would be much better of course.
The CallInterceptor expects to receive the configuration stored in appsettings.json or similar it is injected using Options pattern
We will first construct the options object programatically:
var options = Options.Create(new CallInterceptorOptions
{
ServiceName = "google.protobuf.CustomerService",
ResponseType = "GetCustomerByIdResponse",
JsonResponseContent = JsonConvert.SerializeObject(new GetCustomerByIdResponse { Customer = new Customer { Id = 1, FirstName = "Ed", LastName = "Torsten" } })
});
The configuration in appsettings.json would look like this:
{
"CallInterceptorOptions": {
"ServiceName": "google.protobuf.CustomerService",
"ResponseType": "GetCustomerByIdResponse",
"JsonResponseContent": "{Customer: {\"Id\":1,\"FirstName\":\"Ed\",\"LastName\":\"Torsten\"}}"
}
}
Now that we have the configuration in place, we can go and create an instance of CallInterceptor:
var channel = new Channel("localhost", 5001, ChannelCredentials.Insecure);
var interceptor = new CallInterceptor(options, channel);
With the CallInterceptor instance ready, we can use it to create our gRPC client
var client = new CustomerService.CustomerServiceClient(interceptor);
Let's imagine that the CustomerService has 2 methods (both Unary):
- GetCustomerById
- GetCustomerByName
Now if we use our instantiated client and try to consume GetCustomerById method it will be intercepted and the predifined response that we configured will be returned. On the other hand trying to consume GetCustomerByName method will work as if the CallInterceptor doesn not exist.
Note: If you are invoking intercepted methods you don't need to have the gRPC server running on the other side.