I have a function that calls a gRPC endpoint, converts the objects into POCO objects and returns them as a list.
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;
}
}
I have been developing a unit test for this function but the list returned always has a count of zero.
This is because the ResponseStream has no elements inside of it.
How can I mock the ResponseStream?
My unit test so far:
[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, 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.
}
}
question from:
https://stackoverflow.com/questions/65917871/mock-grpc-response-stream-for-unit-testing-c-sharp 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…