Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

+1 vote
3.7k views
in Technique[技术] by (71.8m points)

Mock gRPC Response Stream for unit testing - C#

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

2 Answers

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
0 votes
by (110 points)

One possible solution here may be to use mock.qa and mock the entire service with fake data from `.json` files.

Mock.qa is a cloud service (SaaS) that provides a production-ready gRPC mocking server and supports both gRPC and gRPC-web protocols. It offers rich request matching, response templating, and stateful scenarios. You can use a mock for prototyping, development, and testing.

  • Set up in minutes
  • Single YAML config file
  • gRPC-web supported
  • Thrid level DNS routing
Mock.qa is available on GitHub Marketplace:  https://github.com/marketplace/mockqa-grpc/
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...