问题描述
我有一个函数可以调用 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 (将#修改为@)