How to mock an SqlDataReader using Moq - Update

后端 未结 5 1432
温柔的废话
温柔的废话 2021-01-30 17:12

I\'m new to moq and setting up mocks so i could do with a little help. How do I mock up an SqlDataReader using Moq?

Update

After further testing this is what I h

5条回答
  •  面向向阳花
    2021-01-30 17:19

    Inspired by @mikesigs answer and another question: SetupSequence in Moq I've came up with the following extension method that does the work for you:

        public static void SetupDataReader(this Mock dataReaderMock, IList columnNames, ICollection collection)
        {
            var queue = new Queue(collection);
    
            dataReaderMock
                .Setup(x => x.Read())
                .Returns(() => queue.Count > 0)
                .Callback(() =>
                {
                    if (queue.Count > 0)
                    {
                        var row = queue.Dequeue();
                        foreach (var columnName in columnNames)
                        {
                            var columnValue = row.GetType().GetProperty(columnName).GetValue(row);
                            dataReaderMock
                                .Setup(x => x[columnNames.IndexOf(columnName)])
                                .Returns(columnValue);
                            dataReaderMock
                                .Setup(x => x[columnName])
                                .Returns(columnValue);
                        }
                    }
                });
        }
    

    And the usage example:

            var foundTargetIds = new[] { 1, 2, 3 };
            var dataReaderMock = new Mock();
            dataReaderMock.SetupDataReader(new[] { "TargetId" }, foundTargetIds.Select(x => new { TargetId = x }).ToList());
    

提交回复
热议问题