我正在设置 gRPC 客户端。场景是我有一个 REST API,然后使用 gRPC Code First 调用后端服务。但我不知道如何注入模拟 gRPC 服务,以便我可以测试调用 gRPC 服务的代码。理想情况下,我想在program.cs中设置gRPC服务,然后将其注入类库代码中,但我对其他解决方案持开放态度。有什么想法吗?
注意客户端是.Net 6 Web API。
您可以利用
WebApplicationFactory<TEntryPoint>
(参见文档):
共享代码:
using ProtoBuf.Grpc;
using System.Runtime.Serialization;
using System.ServiceModel;
namespace GrpcExperiments.Shared;
[DataContract]
public class HelloReply
{
[DataMember(Order = 1)]
public string? Message { get; set; }
}
[DataContract]
public class HelloRequest
{
[DataMember(Order = 1)]
public string? Name { get; set; }
}
[ServiceContract]
public interface IGreeterService
{
[OperationContract]
Task<HelloReply> SayHelloAsync(HelloRequest request, CallContext context = default);
}
服务器代码:
using ProtoBuf.Grpc;
using GrpcExperiments.Shared;
public class GreeterService : IGreeterService
{
public Task<HelloReply> SayHelloAsync(HelloRequest request, CallContext context = default)
{
return Task.FromResult(new HelloReply { Message = $"Hello {request.Name}" });
}
}
测试代码:
[Fact]
public async Task TestViaGrpcChannel()
{
using var factory = new WebApplicationFactory<Program>();
using var channel = GrpcChannel.ForAddress(factory.Server.BaseAddress, new GrpcChannelOptions
{
HttpClient = factory.CreateClient()
});
var client = channel.CreateGrpcService<IGreeterService>();
var reply = await client.SayHelloAsync(
new HelloRequest { Name = "GreeterClient" });
Assert.Equal("Hello GreeterClient", reply.Message);
}
我尝试使用
GrpcClientFactory
创建客户端服务,但未能成功(请参阅此问题)。