如何解决用于单元测试的模拟 gRPC 响应流 - C#
我有一个函数可以调用 gRPC 端点,将对象转换为 POCO 对象并将它们作为列表返回。
public class ActionPlanConnectionsService : IConnectionService
{
#region Fields
/// <summary>
/// Grpc client
/// </summary>
private readonly ConnectionDb.ConnectionDbClient _client;
#endregion
public ActionPlanConnectionsService(ConnectionDb.ConnectionDbClient channel)
{
_client = channel;
}
public async Task<IEnumerable<Connection>> Get(int actionPlanId,int implementation)
{
List<Connection> diagramConnections = new List<Connection>();
GetConnectionsByIdAndImplementationMessage message = new GetConnectionsByIdAndImplementationMessage
{
ActionPlanId = actionPlanId,Implementation = implementation
};
using var call = _client.GetAllConnections(message);
await foreach (ConnectionServiceModel connection in call.ResponseStream.ReadAllAsync())
{
// Never enters here as ResponseStream has no elements when unit testing!!
diagramConnections.Add(new Connection(
connection.FromActionPlanStepId,connection.ToActionPlanStepId,connection.ActionPlanId,connection.Qualifier,connection.Implementation,connection.Path));
}
return diagramConnections;
}
}
我一直在为此函数开发单元测试,但返回的列表的计数始终为零。 这是因为 ResponseStream 里面没有元素。
如何模拟 ResponseStream?
到目前为止我的单元测试:
[Test]
public async Task GetConnectionstest()
{
// Arrange
Mock<ConnectionDb.ConnectionDbClient> mockClient = new Mock<ConnectionDb.ConnectionDbClient>();
Mock<IAsyncStreamReader<ConnectionServiceModel>> mockResponseStream
= new Mock<IAsyncStreamReader<ConnectionServiceModel>>();
List<ConnectionServiceModel> connectionServiceModels =
new List<ConnectionServiceModel>
{
new ConnectionServiceModel
{
ActionPlanId = 1,FromActionPlanStepId = 1,ToActionPlanStepId = 1,Implementation = 0,Qualifier = 1,Path = " 1;2;3;4;5;6;7;8;9;10;11;12;13;14"
}
};
var fakeCall = TestCalls.AsyncServerStreamingCall
(mockResponseStream.Object,Task.Fromresult(new Metadata()),() => Status.DefaultSuccess,() => new Metadata(),() => { });
mockClient.Setup(m => m.GetAllConnections(
It.IsAny<GetConnectionsByIdAndImplementationMessage>(),null,CancellationToken.None)).Returns(fakeCall);
// Act
ActionPlanConnectionsService service = new ActionPlanConnectionsService(mockClient.Object);
IEnumerable<Connection> connections = await service.Get(1,1);
// Assert
// CONNECTIONS WILL ALWAYS HAVE 0 Elements as the response isn't setup for it.
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。