如何对调用 gRPC 代码优先服务的 .Net 6 代码进行单元测试

问题描述 投票:0回答:1

我正在设置 gRPC 客户端。场景是我有一个 REST API,然后使用 gRPC Code First 调用后端服务。但我不知道如何注入模拟 gRPC 服务,以便我可以测试调用 gRPC 服务的代码。理想情况下,我想在program.cs中设置gRPC服务,然后将其注入类库代码中,但我对其他解决方案持开放态度。有什么想法吗?

注意客户端是.Net 6 Web API。

.net grpc
1个回答
0
投票

您可以利用

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
创建客户端服务,但未能成功(请参阅此问题)。

© www.soinside.com 2019 - 2024. All rights reserved.